JAVA 继承
java继承的概念
Java继承是面向对象的最显著的一个特征。继承是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和行为,
并能扩展新的能力,
继承使用的是extends
因为继承水深,所以记录一下所学
被继承的类叫父类,继承的类叫子类
由于继承,会产生子类覆盖(重写)父类方法的现象。
什么是方法覆盖?
子类中重写父类中已有的方法,即子类重写的方法与父类的方法同名且签名也相同。
声明为final的方法,不允许被子类重写
子类重写父类方法时,访问权限不可以降级
访问权限从高级向低级排列:public > protected > 默认(object) > private
以下是一个实例 转自大佬博客https://blog.youkuaiyun.com/qq_38637725/article/details/83107437
<父类类型> <对象名> = new <子类构造方法>();
<父类类型> <父类对象名> = new <父类构造方法>();
<父类类型> <对象名> = <父类构造方法>();
public class Father {
int num = 0;
public Father() {
System.out.println("Father constructor");
}
public void method() {
System.out.println("Father method()");
}
}
public class Me extends Father {
int num = 1;
public Me() {
System.out.println(“Me constructor”);
}
@Override
public void method() {
System.out.println("Me method()");
}
public void meMethod() {
System.out.println("meMethod()");
}
}
public class PolymorphismDemo {// Polymorphism多态
public static void main(String[] args) {
Father father = new Me();
System.out.println(father.getClass());
System.out.println(father.num);
System.out.println(((Me) father).num);
father.method();
((Me) father).method();
((Me) father).meMethod();
}
}
//结果
Father constructor
Me constructor
class org.westos.Polymorphism.Me
Me method()
Me method()
meMethod()
public class Test {
public static void main(String[] args) {
Me me = new Me();
System.out.println(me.getClass());
Father father = (Father) me;
System.out.println(father.getClass());
System.out.println(((Me) father).getClass());
System.out.println(father.num);
System.out.println(((Me) father).num);
}
}
//结果
Father constructor //理解为初始化时访问先构造器,首先要访问父类构造器,然后再访问子类构造器,不论是子类继承子类还是父类继承子类均是,此后再依次执行。
Me constructor
class org.westos.Polymorphism.Me
class org.westos.Polymorphism.Me
class org.westos.Polymorphism.Me