向上造型
Animal o1 = new Animal ( ) ;
Tiger o2 = new Tiger ( ) ;
Animal o3 = new Tiger ( ;
Tiger o4 = new Animal ( ) ;
父类的引用指向子类的对象
一个子类的对象可以向上造型为父类的对象。即:定义父类型的引用可以指向子类的对象
class Foo {
int value;
public void f ( ) { . . . }
Foo ( int value) {
this . value = value;
}
}
class Goo extends Foo {
int num;
public void g ( ) { . . . }
Goo ( int value, int num) {
super ( value) ;
this . num = num;
}
}
Foo obj = new GOO ( 100 , 3 ) ;
父类的引用可以指向子类的对象,但通过父类的引用只能访问父类所定义的成员,不能访问子类扩展的部分
class Foo {
int value;
public void f ( ) { . . . }
. . . . . . . . .
}
class Goo extends Foo {
int num;
public void g ( ) { . . . }
. . . . . . . . .
}
Foo obj = new Goo ( 100 , 3 ) ;
obj. value = 200 ;
obj. f ( ) ;
obj. num = 5 ;
obj. g ( ) ;
代码
package oo. day03;
public class UpDemo {
public static void main ( String[ ] args) {
Coo o = new Doo ( ) ;
o. c = 5 ;
o. say ( ) ;
}
}
class Coo {
int c;
void say ( ) { }
}
class Doo extends Coo {
int d;
void show ( ) { }
}