高分求助java问题!—引用变量指向子类的实例

来源:百度知道 编辑:UC知道 时间:2024/09/28 06:18:04
class Base{
String var1="变量1"
static String var2="变量2"
void method1()
{System.out.println("方法1"); }
static void method2()
{System.out.println("方法2"); }

class Sup extends Base{
String var3="变量3"
static String var4="变量4"
void method3()
{System.out.println("方法3"); }
static void method4()
{System.out.println("方法4"); }
}
public class Text()
{
public static void mian(){
Base opp1=new Base();
Base opp2= new Sup();
System.out.println("opp1.var1");
System.out.println("opp1.var2");
opp1.method1();
opp1.method2();
System.out.println("opp2.var1");
System.out.println("opp2.var2");
opp2.method1();
opp2.method2();
new Base().method1();/和opp1.method1();有什么区别?
new Base(

先说这样一个基本知识吧。
class A {} /*定义一个类*/
A a; /*定义一个引用,这个引用是类A的引用,但它现在没有引用任何东西,它是null*/
a = new A(); /*new A()创建了一个实例,然后让a引用这个实例*/
关于变量a,或者说引用a,我们说它的静态类型为A,因为我们声明a是用的A a; 我们说a的动态类型也为A,因为a = new A();,所以它引用的动态类型还是A。也就是说,声明一个引用时,类型声明的类型就是它的静态类型,而通过赋值赋给它的一个new X(),X就是它的动态类型。

关于一个类A还不是很明显,因为它的静态类型和动态类型是一样的。那我们再说这样一个例子。
class Base {} class Derived extends Base {}
Base a = new Base();
a = new Derived();
第一句中,a的静态类型和动态类型都是Base;而第二句中,a的静态类型是Base,动态类型则变成了Derived。(同时,第一句中的那个Base对象就丢失了。)

知道静态和动态以后,我们就再来说说多态。所谓多态,顾名思义,就是多种的X态。静态还是动态?显然,对一个引用而言,静态类型是声明的时候就已经确定好的,不能变;那么我们变的只能是动态。那么多态,也就是指,对于一个引用,我们可以根据它不同的动态类型来调用它实际的方法。

class Base { void f() {} }
class Derived extends Base { void f() {} }
Base a = new Base(); a.f();
a = new Derived(); a.f();
看这么一个例子。最开始,a调用的那个f()方法应该是Base类中定义的方法,而后面,a调用的那个f()方法就是Derived类中定义的方法了。原因就是第一次调用时,a的动态类型是Base,而第二次调用时,它的动态类型是Derived了。

这个就是Java中方法的多态。在一个引用上调用方法时,系统会自动找到这个引用引用的