首页 > 代码库 > Java 语法 索引 ----- 继承(Inheritance) 和重写(Overriding)

Java 语法 索引 ----- 继承(Inheritance) 和重写(Overriding)

// Superclass (parent class)class Fruit{    public String flavor;}// Subclass (child class)class Apple extends Fruit {    public String variety;}//downcastingApple a = new Apple();Fruit f = a;Apple c = (f instanceof Apple) ? (Apple)f : null;

 

重写

class Rectangle{    public int w = 10, h = 10;    public int getArea() { return w * h; }}class Triangle extends Rectangle{   //调用父构造函数   public Triangle() { super(); }   @Override    public int getArea() { return w * h / 2; }}Rectangle o = new Triangle();o.getArea(); // (50) calls Triangle‘s version

如果用关键字 final, 比如:  public final int getArea() { return w * h; } 这个方法不能被子类重写.

 

 

参考文献: Java Quick Syntax Reference by Mikael Olsson