java之动态绑定和静态绑定

如下面代码:

package cn.lifx.test;

public class Test 
{
	public static void whichFoo(Base arg1, Base arg2) 
	{
		arg1.foo(arg2);
	}

	public static void main(String[] args) 
	{
		Base b = new Base();
		Derived d = new Derived();

		whichFoo(b, b);
		whichFoo(b, d);
		whichFoo(d, b);
		whichFoo(d, d);
	}
}

class Base 
{
	public void foo(Base x) 
	{
		System.out.println("Base.Base");
	}

	public void foo(Derived x) 
	{
		System.out.println("Base.Derived");
	}
}

class Derived extends Base 
{
	public void foo(Base x) 
	{
		System.out.println("Derived.Base");
	}

	public void foo(Derived x) 
	{
		System.out.println("Derived.Derived");
	}
}

 

 

输出为:

Base.Base
Base.Base
Derived.Base
Derived.Base

 

 

如下面代码:

package cn.lifx.test;

public class Test 
{
	public static void whichFoo(Base arg1, Base arg2) 
	{
		arg1.foo(arg2);
	}

	public static void main(String[] args) 
	{
		Base b = new Base();
		Base base = new Derived();
		Derived d = new Derived();
		
		base.foo(b);
		base.foo(d);
		d.foo(b);
		d.foo(base);
		
		System.out.println();
		
		whichFoo(b, b);
		whichFoo(b, d);
		whichFoo(d, b);
		whichFoo(d, d);
	}
}

class Base 
{
	public void foo(Base x) 
	{
		if(x instanceof Derived)
		{
			System.out.println("Base.Derived");
		}
		else if(x instanceof Base)
		{
			System.out.println("Base.Base");
		}
	}
}

class Derived extends Base 
{
	public void foo(Base x) 
	{
		if(x instanceof Derived)
		{
			System.out.println("Derived.Derived");
		}
		else if(x instanceof Base)
		{
			System.out.println("Derived.Base");
		}
	}
}

  

输出为:

Derived.Base
Derived.Derived
Derived.Base
Derived.Derived

Base.Base
Base.Derived
Derived.Base
Derived.Derived

 

你可能感兴趣的:(java)