已知下面的水果类,请设计一个类继承该类,添加新的属性,并对eat方法进行重写。写一个主类测试子类对象的重写的方法、
public class Fruit {
String type;
public void eat() {
System.out.println("水果怎么吃?");
}
}
已知下面的水果类,请设计一个类继承该类,添加新的属性,并对eat方法进行重写。写一个主类测试子类对象的重写的方法、
public class Fruit {
String type;
public void eat() {
System.out.println("水果怎么吃?");
}
}
理解继承:继承的目的是复用父类中的代码,语法 public class SubClass extends SupClass{}
,其中 SubClass
是子类名,SupClass
是父类名。
理解重写:重写的原因是父类中的方法不适用于子类,语法上需要保证子类方法签名和父类保持一致。
示例代码如下:
public class Fruit {
private String type;
public Fruit(String type) {
this.type = type;
}
public void eat() {
System.out.println("水果怎么吃?");
}
}
public class Banana extends Fruit {
private String color;
public Banana(String color) {
super("香蕉");
this.color = color;
}
@Override
public void eat() {
System.out.println("香蕉剥皮吃");
}
}
public class Main {
public static void main(String[] args) {
Fruit fruit = new Banana("黄");
fruit.eat();
}
}