面向对象_继承的注意项和什么时候使用继承

来源:互联网 发布:淘宝货到付款订单快递 编辑:程序博客网 时间:2024/05/17 03:46
/*继承的注意事项:A:子类只能继承父类所有非私有的成员(成员方法和成员变量)B:子类不能继承父类的构造方法,但是可以通过super关键字去访问父类的构造方法。C:不要为了部分功能而去继承class A {public void show1(){}public void show2(){}}class B{public void show2(){}public void show3(){}}//我们发现B类中出现了和A类一样的show2()方法,所以,我们就用继承来体现class B extends A{public void show(){}}//这样其实不好,因为这样你不但有了show2(),还多了show1()。有可能show1()不是你想要的那么,我们什么时候考虑使用继承?继承其实体的是一种关系:"is a"。PersonStudentTeacher水果苹果香蕉橘子采用假设法。如果有两个类A,B。只有他们符合A是B的一种,或者B是A的一种,就可以考虑使用继承*/class Father {private int num = 10;public int num2 = 20;//私有方法,子类不能继承private void method(){System.out.println(num);System.out.println(num2);}public void show(){System.out.println(num);System.out.println(num2);}}class Son extends Father {public void function() {// num 可以在 Father 中访问 private// System.out.println(num); //了类不能继承父类的私有成员变量System.out.println(num2);}}class ExtendsDemo3 {public static void main(String[] args){//创建对象Son s = new Son();//s.mathod(); //子类不能继承父类私用成员方法s.show();System.out.println("-----------");s.function();}}

1 0
原创粉丝点击