本文實例講述了java對象轉型的概念,分享給大家供大家參考。具體方法如下:
對象轉型(casting)注意事項如下:
1、一個基類的引用類型變量可以“指向”其子類的對象。
2、一個基類的引用不可以訪問其子類對象新增加的成員(屬性和方法)。
3、可以使用 引用變量 instanceof 類名 來判斷該引用型變量所“指向”的對象是否屬于該類或該類的子類。
4、子類的對象可以當做基類的對象來使用稱作向上轉型(upcasting),反之成為向下轉型(downcasting)。
具體實現代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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程序設計有所幫助