或許大家java的多態問題,對上溯,下溯造型有了一定的概念,對protect和private大家想必也很清楚,但是,這幾個個結合在一起,往往令人產生很多困惑,在這裡,我舉一個例子,大家或許會發覺這篇文章對你來說還是很有意義的:
例子一共有兩個class. 可能出現困惑的地方我都會在後面一一解釋。
A是一個父類,B繼承A,並且實現了protectedTest(Object obj)方法.如下面所示:
B.java的原始碼:
package cn.org.matrix.test;
import cn.org.matrix.test.A;
/**
* <p>Title: protect, private and upcasting </p>
* <p>Description: email:chris@matrix.org.cn</p>
* <p>Copyright: Matrix Copyright (c) 2003</p>
* <p>Company: Matrix.org.cn</p>
* @author chris
* @version 1.0,who use this example pls remain the declare
*/
public class B extends A
{
protected int protectedb = 0;
protected int protectedab = 0;
protected void protectedTest(Object obj)
{
System.out.println("in B.protectedTest(Object):" + obj);
}
}
A.java的原始碼:
package cn.org.matrix.test;
import cn.org.matrix.test.B;
/**
* <p>Title: protect, private and upcasting </p>
* <p>Description: email:chris@matrix.org.cn</p>
* <p>Copyright: Matrix Copyright (c) 2003</p>
* <p>Company: Matrix.org.cn</p>
* @author chris
* @version 1.0,who use this example pls remain the declare
*/
public class A
{
protected int protecteda = 0;
protected int protectedab = 0;
private void privateTest()
{
System.out.println("in A.privateTest()");
}
protected void protectedTest(Object obj)
{
System.out.println("in A.protectedTest(Object):" + obj );
}
protected void protectedTest( String str )
{
System.out.println("in A.protectedTest(String):" + str);
}
public static void main (String[] args)
{
// Test A
A a1 = new A();
a1.privateTest();
// Test B
String helloStr = "Hello";
Object helloObj = helloStr;
B b1 = new B();
A a2 = b1; // 這裡發生了什嗎?困惑1
b1=a1; //編譯錯誤,困惑2
b1. privateTest(); //編譯錯誤,困惑3
b1.protectedTest(helloObj); //輸出結果?困惑4
b1.protectedTest(helloStr); //編譯錯誤,困惑5
a2.protectedTest(helloObj); //輸出結果? 困惑6
a2.protectedTest(helloStr); //輸出結果?困惑7 ?
}
}