4. 只支持单继承,不支持多继承。
//class Son exnteds Father {} //单继承,正确的//class Son extends Father,Mother {} //多继承,错误的5. Java支持多层继承(继承体系)
java继承的注意事项
6. 子类只能继承父类所有非私有的成员(成员方法和成员变量)7. 子类不能继承父类的构造方法;但是可以通过super关键字去访问父类的构造方法。
8. 不要为了部分功能而去继承。
/*
class A {
public void show1(){};
public void show2(){};
}
class B {
public void show2(){}; //我们发现B类中出现了和A类一样的show2()方法,所以,我们就用继承来体现
public void show3(){};
}
//这样其实不好,因为这样你不但有了show2(),还多了show1()。有可能show1()不是你想要的。
class B extends A {
public void show3(){};
}
*/
继承体现的是一种关系"is a";比如student is person,teacher is person;
或者apple is fruits,banana is fruits;
采用假设法,如果有两个类A,B,只有他们符合A是B的一种,或者B是A的一种,就可以考虑使用继承。
未使用继承
使用继承之后
代码详解:
//只能单继承,不能多继承,但是可以多层继承。
class GrandFather{
public void show(){
System.out.println("我是爷爷");}}
class Father extends GrandFather{
public void method(){
System.out.println("我是老子");}}
class Son extends Father{}
class ExtendsDemo2{
public static void main(String[] args){
Son s =newSon();
s.method();//使用父亲的
s.show();//使用爷爷的}}