Java basic study notes _ inherited characteristics

1. Classes can only be inherited

Java only supports single inheritance of classes , but supports multiple inheritance.

Java supports multiple inheritance of interfaces , the syntax is: interface A extends interface B, interface C, interface D,...

public class Fruit { //水果类
}

public class Apple extends Fruit {//苹果类
}

public class Orange extends Fruit { //橘子类
}

public class Fuji extends Apple { //红富士苹果类
}

public class GreenApple extends Apple { //青苹果类
}

2. Cannot inherit the private properties and methods of the parent class

The subclass can only inherit the non-private properties and methods of the parent class.

The subclass can have its own attributes and methods, that is, the subclass can extend the parent class.

Subclasses can implement the methods of the parent class in their own way.

public class Fruit { //水果类
    private String pri ;
    public void test() {
        System. out.println(0);
    }
}

public class Apple extends Fruit { //苹果类
    private String color;
    public void eat() {
        System.out.println("I wanna to eat a" + color + "apple.");
    }
}

public class Test { //测试类
    public static void main(String[] args){
        Apple a = new Apple();
        //System.out.println(a.pri) ; //报错
        a.test() ;
    }
}

3. Cannot inherit the construction method of the parent class

4. Inheritance embodies the relationship of "is a"

5. Improve the coupling between classes (the shortcomings of inheritance, high coupling will cause the closer the connection between the codes, the worse the code independence).

Guess you like

Origin blog.csdn.net/qq_43191910/article/details/114760618