I have a question about succession and casting in java. I have the following two example classes and one test class, and I tell my question after class:
public class automobile {public perfection; Public Automobile () {var = 1; } Public string toasting () {return "Automobile:" + var; }} Public Class Porsche Automobile [Public Ent War; Public porsche () {var = 2; } Public string toString () {return "Porsche:" + var; }} Public Sector Exam {Public Stable Zero Main (String [] Args) {Porsche P = New Porsche (); Automobile A = new automobiles (); System.out.println ("(Automobile) P =" + (Automobile) P); System.out.println ("(Automobile) P. Var =" + ((Automobile) P) .var); }}
Output is:
(Automobile) P = Porsche: 2 (Automobile) p.var = 1
< P> I do not understand why we have 1 in the second statement? Should not it be 2? Because in the first statement when I drink automobiles, I still get the form of a representation of PORSCHE: 2
as p
- I understand it in the following way: Still I have put p
in the automobile P
"its original nature" - p
the purpose of class Porsche But because Porsche's expansion is automobile, we can say that P is also an automobile and so when we have it clear In the automobile, if you put it in the automobile, then its methods continue to be used - in our case, the method toString ()
is defined in Porsche
On the other hand, if I write, , Then the second print statement should be given 2 and 1 no.
Now it is a contradiction to me, but it works in Java, it seems that I do not know what is happening during casting and heritage process.
I believe that you can not actually override the variable in Java The subclasses are actually ' var'
. Hides.
When you enter Automobile
, you get the superclass version var
variable, however, toString ()
method Still looking at the version of the example var
variable.
If you removed Public Ink Word from Porsche Subclasses
it should work as expected.
It should be noted that this is not a good practice to use public frequency variables, you should always create gates / sets to make it right.
Comments
Post a Comment