In Java, polymorphism is the ability of the same behavior to have multiple different manifestations or forms; polymorphism is the same interface, using different instances to perform different operations. The advantages of polymorphism: 1. Eliminate coupling relationships between types; 2. Replacement; 3. Extensibility; 4. Interface; 5. Flexibility; 6. Simplification.
The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.
1. Polymorphism is the third major feature of object-oriented after encapsulation and inheritance.
2. PolymorphismPractical meaningUnderstanding:
Real things often take on multiple forms, such as students , students are a kind of people, then a specific classmate Zhang San is both a student and a person, that is, there are two forms. The language of objects can also describe multiple forms of a thing. If the Student class inherits the Person class, a Student object is both a Student and a Person.
The parent class reference variable can point to the subclass object
.Note: When calling a method using a polymorphic parent class reference variable, the rewritten method of the subclass will be called.
5. Definition and usage format of polymorphismDefinition format:Parent class type variable name=new subclass type();
6. Understand:Polymorphism is the ability of the same behavior to have multiple different manifestations or forms.
# #Characteristics of members in polymorphism
Fu f=new Zi(); System.out.println(f.num);//f是Fu中的值,只能取到父中的值
Fu f1=new Zi(); System.out.println(f1.show());//f1的门面类型是Fu,但实际类型是Zi,所以调用的是重写后的方法。
Fu f1=new Zi(); Fu f2=new Son(); if(f1 instanceof Zi){ System.out.println("f1是Zi的类型"); } else{ System.out.println("f1是Son的类型"); }
Polymorphic transformation
Polymorphism The transformation is divided into two types: upward transformation and downward transformation.
package day0524; public class demo04 { public static void main(String[] args) { People p=new Stu(); p.eat(); //调用特有的方法 Stu s=(Stu)p; s.study(); //((Stu) p).study(); } } class People{ public void eat(){ System.out.println("吃饭"); } } class Stu extends People{ @Override public void eat(){ System.out.println("吃水煮肉片"); } public void study(){ System.out.println("好好学习"); } } class Teachers extends People{ @Override public void eat(){ System.out.println("吃樱桃"); } public void teach(){ System.out.println("认真授课"); } }
What is the result of running the project? Java video tutorial The above is the detailed content of How to understand java polymorphism. For more information, please follow other related articles on the PHP Chinese website!package day0524;
public class demo1 {
public static void main(String[] args) {
A a=new A();
a.show();
B b=new B();
b.show();
}
}
class A{
public void show(){
show2();
}
public void show2(){
System.out.println("A");
}
}
class B extends A{
public void show2(){
System.out.println("B");
}
}
class C extends B{
public void show(){
super.show();
}
public void show2(){
System.out.println("C");
}
}