java in the multi-state mechanism , first of all I would like to ask a polymorphic method is only for you ? Cast member variable count polymorphism ?
Then for polymorphism , although able to read , but can not figure out some issues , seeking predecessors to the point explanation. My question is that : the child object to the parent object is instantiated , if the parent object and child objects have the same variables and methods, but invoked, access variables of the parent class , the access method is to subclass . I know that you want to visit the child in front of the class cast needs to be done , the latter because of dynamic binding . But why is there such a difference in java it ? Or because java is so variable and methods for setting mechanisms were it ?
new talent began to learn , seeking advice ! Thank you !
Code:
1.
import static java.lang.System. *;
class Car
{String aMember = " I am a car class member variables " ;
}
class Truck extends Car {String aMember = " I am a truck class variables , automobiles also have" ;
}
public class c43
{
public static void main (String [] args)
{Car c = new Truck (); out.println (c.aMember);
}
}
This test result is " I'm a car class variable " access by default is the parent class members.
2. Code 2
import static java.lang.System. *;
class Test {
public String name; public Test () {};
public void setName (String n)
{
this.name = n; out.println (" in the parent class " ) ;
}
public String getName ()
{
return this.name;
}
}
public class c44 extends Test
{public void setName (String name)
{
out.println (" subclass called setName, this is also in the parent class " ) ;
}
public static void main (String [] args)
{
c44 child = new c44 ();
Test test [] = new Test [2];
test [0] = child;
test [0]. setName ("silence");
test [1] = new Test ();
}
}
This visit is a subclass setname, the output of the " sub-class called setname".
------ Solution ---------------------------------------- ----
polymorphism showed method override .
and membership does not matter.
polymorphic expression inheritance relationship .
------ Solution ---------------------------------------- ----
polymorphism is reflected in the way , the landlord said not polymorphic , non- object-oriented languages can be done casts .
------ For reference only -------------------------------------- -
Thank you, I also think that polymorphism method , after all, is through C + + virtual functions to achieve. Because behavioral approach embodied by the message , but we are not like the teacher said . . Really, lost to him. Thank you !
------ For reference only -------------------------------------- -
I did not say polymorphism method , my original words are expressed as polymorphic method overrides ( and occurred in the base class and derived classes directly ...),
没有评论:
发表评论