對Java多態性綜合運用的探討

來源:互聯網
上載者:User

或許大家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 ?
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.