A multi-state
1.1 concept:
Polymorphism is the second encapsulation, inheritance, object-oriented third characteristic.
For example: Student class inherits Human class, then the Student object is both a Student is also a Human.
State reflects more than 1.2
Code format:
父类引用变量指向子类对象,Student对象可以赋值给Student也可以赋值给Human
父类类型 变量名 = new 子类类型();
Human s = new Student();
Polymorphic premise: it must be inherited (to achieve) relations
It features more than 130 member states of the variables
When a member variable of the same name appear the child the parent class,
compile-time: whether there is a reference to the parent class member variable, if not then fail to compile
run time: call the parent class member variables in
a nutshell : compile and run all look left
Features over 1.4 states member methods
When a member of the same name appear the way the child the parent class,
compile-time: whether there is a reference to the members of the parent class method, if not then fail to compile
runtime: method is invoked after the subclass overrides
a nutshell : Compile look left, look to the right to run
Transition state more than 1.5
Polymorphic transition and the downward transition into upcast
1, upcast:
Process subclass object when assigned to the parent class reference variable, the transition is upward, polymorphic transformation itself up.
format:
父类类型 变量名 = new 子类类型();
2, downcast:
a transition has upwardly subclass object casts can be used, the parent class into subclasses reference variable references, this process is downcast. Or directly create a subclass of a parent class object is not the downcast.
Note: If no polymorphism in the case, turned into a strong parent class subclasses ClassCastException occur.
Use instanceof to judge before a strong turn, can be avoided ClassCastException
format:
父类类型 变量名 = new 子类类型();
子类类型 变量名 = (子类类型)父类的变量;
More than 160 state benefits and drawbacks
Benefits: Hide the sub-class type, improves the scalability of the code
Disadvantages: Unless downcast, otherwise it will not peculiar to members of the subclass
1.7 Keyword instanceof
format:
对象名 instanceof 类型
Action: determining whether the object belongs to a specified class
Use instanceof possible
- Compilation failed:
- Non-polymorphic, other subclass object inheritance hierarchy in Comparative
- Class inheritance hierarchy than the objects to compare
- false: the polymorphic other subclass object inheritance hierarchy are compared
- true:
- Non-polymorphic, compared with the object class itself
- Non-polymorphic, the object compared with the parent
- Multi-state, compared with the object itself, the parent class or classes