class Super
{
static String greeting(){
return "Super Say Hello";
}
String name(){
return "My Name is Super";
}
}
class Sub extends Super
{
static String greeting(){
return "Sub Say Hello World";
}
String name(){
return "My Name is Sub";
}
}
public class Test
{
public static void main(String[] args)
{
Super s1=new Sub();
System.out.println("Super s1=new Sub():"+s1.greeting()+",\t"+s1.name());
Super s2=new Super();
System.out.println("Super s2=new Super()"+s2.greeting()+",\t"+s2.name());
Sub s3=new Sub();
System.out.println("Sub s3=new Sub():"+s3.greeting()+",\t"+s3.name());
//Sub s4=new Super();//错误
//System.out.println("Sub s4=new Super():"+s4.greeting()+",\t"+s4.name());
}
}
结果:
Super s1=new Sub():Super Say Hello, My Name is Sub
Super s2=new Super()Super Say Hello, My Name is Super
Sub s3=new Sub():Sub Say Hello World, My Name is Sub
Sub s4=new Super();//错误因为这涉及到了多态的问题,在多态之中父类引用可以指向子类对象,而且子类对象可以复写了父类中的方法,但是你不像这样定义定义子类对象指向父类,这是不对的,当你使用子类复写的方法时其实父类中的方法还在。你定义的greeeting是静态的是属于类的,你用super类型的对象调用时输出super对象的greeting方法。然而name()方法不是静态的是属于对象的,因此当你使用多态来调用name()方法时,其实是调用被子类复写的方法因此输出 My Name is Sub
因此System.out.println("Super s1=new Sub():"+s1.greeting()+",\t"+s1.name());
输出Super s1=new Sub():Super Say Hello, My Name is Sub