1、题目
题目非常简单,里面主要是记录我遇到的一个问题
2、源代码
Computer类
package com.train; //自动补全alt+/ 快捷注释ctrl+/ 删除行ctrl+d 复制行ctrl+alt+向下键 //导入需要的类alt+enter 快速格式化代码ctrl+alt+l 快速运行alt+r //生成构造器alt+insert 查看类的层次关系ctrl+h 快速定位方法ctrl+b //自动分配变量名 后面加.var //模板快捷键 soutm main public class Computer { private String cpu; private int memory; private int disk; public Computer(String cpu, int memory, int disk) { this.cpu = cpu; this.memory = memory; this.disk = disk; } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public int getMemory() { return memory; } public void setMemory(int memory) { this.memory = memory; } public int getDisk() { return disk; } public void setDisk(int disk) { this.disk = disk; } public String getDetails(){ return "电脑的cpu是"+cpu+"内存"+memory+"硬盘是"+disk; } }
PC类
package com.train; public class PC extends Computer{ private String brand; public PC(String cpu, int memory, int disk, String brand) { super(cpu, memory, disk); this.brand = brand; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public void printInfo(){ System.out.println(getDetails()+" brand"+brand); } }
NotePad类
package com.train; public class NotePad extends Computer{ private String color; public NotePad(String cpu, int memory, int disk, String color) { super(cpu, memory, disk); this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void printInfo(){ System.out.println(getDetails()+" color"+color); } }
Test类
package com.train; public class Test { public static void main(String[] args) { PC pc = new PC("i5",8,50,"华硕"); NotePad notePad = new NotePad("i5",8,50,"黑色"); pc.printInfo(); notePad.printInfo(); } }
踩的坑:
在Computer类中,最后getDetails()方法我一开始用的void返回类型,方法体用的
System.out.println实现,但在继承了Computer类的PC类中在printInfo()方法中返回类型为void,且方法体中是System.out.println(getDetails()+" brand"+brand);会报错。
解决方法:
Computer类getDetails()方法用String返回类型,方法体中用return