父类的引用指向子类的对象
方法只能使用父类的
public class Exec{
public static void main(String[] args){
Animal ani = new Dog( );
// ani 只能调用方法sound 和 run
ani.sound( );
ani.run( );
}
}
class Animal{
void sound( ){
System.out.println("Sound");
}
void run( ){
System.out.println("Run");
}
}
class Dog{
void sound( ){
System.out.println("Barf");
}
void eat( ){
System.out.println("Bone");
}
}
如果想调用子类的方法,则需要强制转换类型
public class Exec{
public static void main(String[] args){
Animal ani = new Dog( );
// ani.sound( ) 输出打印Barf而不是Sound
ani.sound( );
}
}
class Animal{
void sound( ){
System.out.println("Sound");
}
void run( ){
System.out.println("Run");
}
}
class Dog{
void sound( ){
System.out.println("Barf");
}
void eat( ){
System.out.println("Bone");
}
}
如果子类重写了父类的方法, 则执行子类的方法
public class Exec{
public static void main(String[] args){
Animal ani = new Dog( );
// ani 如果想调用eat,则需要首先强制类型转换策成Dog类
(Dog)ani.eat( );
}
}
class Animal{
void sound( ){
System.out.println("Sound");
}
void run( ){
System.out.println("Run");
}
}
class Dog{
void sound( ){
System.out.println("Barf");
}
void eat( ){
System.out.println("Bone");
}
}