Java课程03总结
一:繼承條件下的構(gòu)造方法調(diào)用
package test;class Grandparent {public Grandparent(){System.out.println("GrandParent Created.");}public Grandparent(String string) {System.out.println("GrandParent Created.String:" + string);}}class Parent extends Grandparent {public Parent(){//super("Hello.Grandparent.");System.out.println("Parent Created");// super("Hello.Grandparent."); } }class Child extends Parent {public Child(){System.out.println("Child Created");} }public class TestInherits {@SuppressWarnings("unused")public static void main(String args[]){Child c = new Child();} }?
通過(guò) super 調(diào)用基類(lèi)構(gòu)造方法(
通過(guò) super 調(diào)用基類(lèi)構(gòu)造方法,必須是子類(lèi)構(gòu)造方法中的第一個(gè)語(yǔ)句。
)后運(yùn)行截圖:
如果super()語(yǔ)句不在第一行,報(bào)錯(cuò):Constructor call must be the first statement in a constructor。
?
二:方法覆蓋
package test;class Pa {public void display(){System.out.println("Parent Created");} }class Ch extends Pa {public void display(){super.display();System.out.println("Child Created");} }public class Override {public static void main(String[] args) {// TODO Auto-generated method stubCh c = new Ch();c.display();} }
在子類(lèi)中,若要調(diào)用父類(lèi)中被覆蓋的方法,可以使用super關(guān)鍵字。
運(yùn)行結(jié)果:
?
沒(méi)有調(diào)用父類(lèi)中被覆蓋的方法
運(yùn)行結(jié)果:
三:類(lèi)型轉(zhuǎn)換
package test;class Mammal{} class Dog extends Mammal {} class Cat extends Mammal{}public class TestCast {public static void main(String args[]){Mammal m;Dog d=new Dog();Cat c=new Cat();m=d;//d=m;d=(Dog)m;//d=c;//c=(Cat)m; } }結(jié)果:
?
結(jié)論:
子類(lèi)對(duì)象可以直接賦給基類(lèi)變量。
?
基類(lèi)對(duì)象要賦給子類(lèi)對(duì)象變量,必須執(zhí)行類(lèi)型轉(zhuǎn)換,
其語(yǔ)法是: 子類(lèi)對(duì)象變量=(子類(lèi)名)基類(lèi)對(duì)象名;
?
?四:子類(lèi)父類(lèi)擁有同名的方法
package test;public class ParentChildTest {public static void main(String[] args) {Parent parent=new Parent();parent.printValue();Child child=new Child();child.printValue();parent=child;parent.printValue();parent.myValue++;parent.printValue();((Child)parent).myValue++;parent.printValue();} }class Parent{public int myValue=100;public void printValue() {System.out.println("Parent.printValue(),myValue="+myValue);} } class Child extends Parent{public int myValue=200;public void printValue() {System.out.println("Child.printValue(),myValue="+myValue);} }運(yùn)行結(jié)果:
結(jié)論:
當(dāng)子類(lèi)與父類(lèi)擁有一樣的方法,并且讓一個(gè)父類(lèi)變量引用一個(gè)子類(lèi)對(duì)象時(shí),到底調(diào)用哪個(gè)方法,由對(duì)象自己的“真實(shí)”類(lèi)型所決定,這就是說(shuō):對(duì)象是子類(lèi)型的,它就調(diào)用子類(lèi)型的方法,是父類(lèi)型的,它就調(diào)用父類(lèi)型的方法。
?
轉(zhuǎn)載于:https://www.cnblogs.com/janeszj/p/9890533.html
總結(jié)
以上是生活随笔為你收集整理的Java课程03总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringBootStarter种类
- 下一篇: flink on yarn部分源码解析