父类 xx = new 子类()与子类 xx = new 子类()的区别

来源:互联网 发布:淘宝虚拟发布类目 编辑:程序博客网 时间:2024/04/30 18:39

在java中我们经常遇到父类 xx = new 子类()的定义对象,那么与子类 xx = new 子类()相比有什么区别呢,下面我们从代码分析:

package com.sky.java;


public class FatherNewSon
{


/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
       a ta = new b();
       b tb = new B();
       ta.test();
       ta.son();
       tb.test();
       tb.son();
}
    
    
}
class a{
public a()
{
 
}
public void test()
{
 System.out.println(this.getClass().getName());
}
}


class b extends a{
public b()
{

}
public void son()
{
System.out.println("son"); 
}
}

其中ta是由父类定义的指向子类对象的引用,tb是由子类 xx = new 子类()定义的,然而ta.son()却报错:没有该方法,而tb.son()却不会报错。可见,父类 xx = new 子类()定义的对象无法调用非从父类继承的方法。此外,由运行结果:


可见ta.test()和tb.test()都是调用b中的方法。

以上总结出父类 xx = new 子类()与子类 xx = new 子类()的区别:

1.父类 xx = new 子类()定义的对象只能调用继承来的方法。

2.父类 xx = new 子类()定义的对象调用的是子类的方法,而不是父类的。

2 0