Perhaps everyone Java polymorphic problem, on the trace, the next retrospective modelling has a certain concept, to protect and private everyone must also be very clear, but, these several together, often cause a lot of confusion, here, I give an example, You may find this article to be of great significance to you:
Example a total of two class. Where there may be confusion I will explain in the back one by one.
A is a parent class, B inherits a, and implements the Protectedtest (Object obj) method. As shown in the following:
B.java's source code:
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's source code:
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;
Protect ed 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;//What's going on here? Puzzle 1
B1=A1//Compile error, puzzle 2
B1. privatetest ();//Compile error, puzzle 3
B1.protectedtest (helloobj);//output result? Puzzle 4
B1.protectedtest (HELLOSTR); Compile error, Puzzle 5
A2.protectedtest (helloobj);//output result? Confused 6
A2.protectedtest (HELLOSTR)//output? Confusing 7?
}
}