2013年9月10日星期二

java member variables in the method of value


class Parent {
int x = 10;
public Parent() {
add(2);
}
void add(int j) {
this.x += j;
}
}
class Child extends Parent {
int x = 9;

void add(int j) {
System.out.println("==+++=="+x);//为什么这里输出的x是0
x += j;
System.out.println("===="+x)
}
public Child(){
super();
System.out.println(">>>>>>"+x);
}
}
public class Test {
public static void main(String args[]) {
Parent p = new Child();
System.out.println(p.x);//为什么结果是10,不是说多态父类引用指向子类对象吗?


}
}

issue see note above
------ Solution ------------------- -------------------------
personal view:
"System.out.println (" == + + + == "+ x) ;/ / why there output x is 0"
This is a class initialization problem , the landlord refer to:
http://wenwen.soso.com/z/q191435823.htm

"System.out.println (px) ;/ / why the result is 10 , not that polymorphic parent class subclass object reference points do ? "
For multi -state , I remember , " Liu Hongwang " The teacher has a formulas , whether or not the landlord be useful !
declare the parent class , subclass ;
statement , what has ; ( attribute )
created what , do what ; ( method )
created what could turn wall why.
------ Solution ---------------------------------------- ----
http://blog.csdn.net/fortheother/article/details/8856976
The second problem I encountered many times .
For the variables, using a reference type.
For the method , the use of the object type.


the first question.
likely an object is created , it first calls the constructor. x = 9; constructor executes completed in only after the completion of x = 9 This code execution.

------ Solution ------------------------------------ --------
System.out.println ("== + + + ==" + x) ;/ / output why there x is 0
understanding of object instantiation process: first instantiated parent class , and then instantiable subclass ; outputs like to understand .
create child object, first create a parent object, so call the parent class constructor when , child of x is the default value 0 instead of 9 . Parent class is instantiated only started after the completion of instantiable subclasses , then x is equal to 9 in the child , so the output is 0 , because the add method in the parent class when called during instantiation , rather than subclasses.

System.out.println (px) ;/ / why the result is 10 , not that polymorphic parent class subclass object reference points do ?
must clear a concept can only be overridden method override ( function ) , can not override attributes. So the parent is still pointing to own properties x, x = 10.
------ For reference only -------------------------------------- -
" wall" should be " strong ."
------ For reference only -------------------------------------- -





are grateful , understanding , and his foundation is not solid

没有评论:

发表评论