例子一共有两个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 ?
}
}
新闻热点
疑难解答