java對象轉型執行個體分析_java

來源:互聯網
上載者:User

本文執行個體講述了java對象轉型的概念,分享給大家供大家參考。具體方法如下:

對象轉型(casting)注意事項如下:

1、一個基類的參考型別變數可以“指向”其子類的對象。

2、一個基類的引用不可以訪問其子類對象新增加的成員(屬性和方法)。

3、可以使用 引用變數 instanceof 類名 來判斷該引用型變數所“指向”的對象是否屬於該類或該類的子類。

4、子類的對象可以當做基類的對象來使用稱作向上轉型(upcasting),反之成為向下轉型(downcasting)。

具體實現代碼如下:

public class TestCasting{  public static void main(String args[]){    Animal animal = new Animal("name");    Cat cat = new Cat("catName","blueColor");    Dog dog = new Dog("dogName","yellowColor");        System.out.println(animal instanceof Animal);    System.out.println(cat instanceof Animal);    System.out.println(dog instanceof Animal);    //System.out.println(animal instanceof cat);  //error        animal = new Dog("dogAnimal","dogColor");    System.out.println(animal.name);    //System.out.println(animal.forColor); //error    System.out.println(animal instanceof Animal);    System.out.println(animal instanceof Dog);    Dog d1 = (Dog)animal;    System.out.println(d1.forColor);   }}class Animal{  public String name;  public Animal(String name){       this.name = name;  }}class Cat extends Animal{  public String eyeColor;  public Cat(String name, String eyeColor){    super(name);    this.eyeColor = eyeColor;  }}class Dog extends Animal{  public String forColor;  public Dog(String name, String forColor){    super(name);    this.forColor = forColor;  }}

運行結果如下圖所示:

希望本文所述對大家的Java程式設計有所協助

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.