日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java课程03总结

發布時間:2025/7/14 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java课程03总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一:繼承條件下的構造方法調用

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();} }

?

通過 super 調用基類構造方法(

通過 super 調用基類構造方法,必須是子類構造方法中的第一個語句。

)后運行截圖:

如果super()語句不在第一行,報錯: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();} }

  

在子類中,若要調用父類中被覆蓋的方法,可以使用super關鍵字。

運行結果:

?

沒有調用父類中被覆蓋的方法

運行結果:

三:類型轉換

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; } }

結果:

?

結論:

子類對象可以直接賦給基類變量。

?

基類對象要賦給子類對象變量,必須執行類型轉換,

其語法是: 子類對象變量=(子類名)基類對象名;

?

?四:子類父類擁有同名的方法

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);} }

運行結果:

結論:

當子類與父類擁有一樣的方法,并且讓一個父類變量引用一個子類對象時,到底調用哪個方法,由對象自己的“真實”類型所決定,這就是說:對象是子類型的,它就調用子類型的方法,是父類型的,它就調用父類型的方法。

?

轉載于:https://www.cnblogs.com/janeszj/p/9890533.html

總結

以上是生活随笔為你收集整理的Java课程03总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。