Home> Java> javaTutorial> body text

Master JAVA object-oriented polymorphism in one article

WBOY
Release: 2022-06-15 11:48:11
forward
1886 people have browsed it

This article brings you relevant knowledge aboutjava, which mainly introduces related issues about polymorphism. Polymorphism is an important feature of object-oriented programming and points to the same entity. Having multiple forms at the same time refers to the multiple forms of objects. Let’s take a look at them together. I hope it will be helpful to everyone.

Master JAVA object-oriented polymorphism in one article

Recommended study: "java Video Tutorial"

1. Concept

Polymorphism is an object-oriented program An important feature of design (OOP) is that the same entity has multiple forms at the same time, that is, the same object represents different objects at different times, which refers to the multiple forms of the object.

You can treat different subclass objects as parent classes, thereby shielding the differences between different subclass objects, writing common code, making common programming, and unifying calling standards.

For example, your girlfriend asks you to buy some fruit. No matter what you buy is an apple or a watermelon, as long as it is fruit, this is a manifestation of polymorphism in life.

For another example, We can classify kittens, puppies, and piglets into small animals. Each small animal needs to eat, so we can uniformly set that they all must eat, but the habits of each small animal are different, so this is It can be set to the unique function of the small animal. The polymorphic object can only call the functions overridden in the subclass defined in the parent class, and cannot call the unique functions of the subclass. This achieves the unification of the code

2. Characteristics

  1. Prerequisite for polymorphism 1: Inheritance
  2. Prerequisite for polymorphism 2: Method overriding
  3. The parent class reference points to the subclass Object, such as: Animal a = new Cat();
  4. In polymorphism, look at the left when compiling and the right when running
    Master JAVA object-oriented polymorphism in one article

3. Exercise: Polymorphism Getting Started Case

Create package: cn.tedu.oop
Create class: TestDemo.java

package cn.tedu.oop2;/*本类用作多态的入门案例*/public class TestDemo { public static void main(String[] args) { //6.创建“纯纯的”对象用于测试 Animal a = new Animal(); Cat c = new Cat(); Dog d = new Dog(); a.eat();//小动物Animal吃啥都行~调用的是父类自己的功能 c.eat();//小猫爱吃小鱼干~调用的是子类重写后的功能 d.eat();//小狗爱吃肉骨头~调用的是子类重写后的功能 /*2.父类对象不可以使用子类的特有功能*/ //a.jump();//报错,Animal类里并没有这个方法 //a.run();//报错,Animal类里并没有这个方法 c.jump();//小猫Cat跳的老高啦~,子类可以调用自己的功能 d.run();//小狗Dog跑的老快啦~,子类可以调用自己的功能 //7.创建多态对象进行测试 /*3.口诀1:父类引用指向子类对象 * 解释:创建出来的子类对象的地址值,交给父类类型的引用类型变量来保存*/ Animal a2 = new Cat();//Cat类对象的地址值交给父类型变量a2来保存 Animal a3 = new Dog();//Dog类对象的地址值交给父类型变量a3来保存 //8.测试多态对象 /*4.口诀2:编译看左边,运行看右边 * 解释:必须要在父类定义这个方法,才能通过编译,把多态对象看作是父类类型 * 必须要在子类重写这个方法,才能满足多态,实际干活的是子类*/ a2.eat();//小猫爱吃小鱼干~,多态对象使用的是父类的定义,子类的方法体 }}/*1.多态的前提:继承+重写*///1.创建父类class Animal{ //3.创建父类的普通方法 public void eat(){ System.out.println("小动物Animal吃啥都行~"); }}//2.1创建子类1class Cat extends Animal{ //4.1添加重写的方法 public void eat(){ System.out.println("小猫爱吃小鱼干~"); } //5.1添加子类的特有功能 public void jump(){ System.out.println("小猫Cat跳的老高啦~"); }}//2.2创建子类2class Dog extends Animal{ //4.2添加重写的方法 @Override public void eat(){ System.out.println("小狗爱吃肉骨头~"); } //5.2添加子类的特有功能 public void run(){ System.out.println("小狗Dog跑的老快啦~"); }}
Copy after login

4. The benefits of polymorphism

  1. Polymorphism can Let us not care about the specific type of an object, we can use certain methods of the object
  2. Improves the scalability and maintainability of the program

5. The use of polymorphism

Premise: The polymorphic object regards itself as the parent class type

  1. member variable: it uses the parent class's
  2. member method: Due to the overwriting phenomenon, the
  3. static members of the subclass are used: they are loaded as the class is loaded, and whoever calls them will return their

6. Exercise: Multiple State members use test

Create package: cn.tedu.oop
Create class: TestDemo2.java

package cn.tedu.oop2;/*本类用于测试多态成员的使用情况*/public class TestDemo2 { public static void main(String[] args) { //7.创建纯纯的子类对象 Dog2 d = new Dog2(); System.out.println(d.sum);//20,子类自己的属性 d.eat();//小狗爱吃肉包子,子类自己的方法 //8.创建多态对象 /*口诀1:父类引用指向子类对象*/ /*口诀2:编译(保存)看左边,运行(效果)看右边*/ Animal2 a = new Dog2(); /*多态中,成员变量使用的是父类的*/ System.out.println(a.sum);//10 /*多态中,方法的声明使用的是父类的,方法体使用的是子类的*/ a.eat();//小狗爱吃肉包子 /*多态中,调用的静态方法是父类的,因为多态对象把自己看作是父类类型 * 直接使用父类中的静态资源*/ a.play();//没有提示,玩啥都行~ Animal2.play(); }}//1.创建父类class Animal2{ //3.创建父类的成员变量 int sum = 10; //4.创建父类的普通方法 public void eat(){ System.out.println("吃啥都行~"); } //9.1定义父类的静态方法play public static void play(){ System.out.println("玩啥都行~"); }}//2.创建子类class Dog2 extends Animal2{ //5.定义子类的成员变量 int sum = 20; //6.重写父类的方法 @Override public void eat(){ System.out.println("小狗爱吃肉包子"); } //9.2创建子类的静态方法play //@Override /*这不是一个重写的方法,只是恰巧在两个类中出现了一模一样的两个静态方法 * 静态方法属于类资源,只有一份,不存在重写的现象 * 在哪个类里定义,就作为哪个类的资源使用*/ public static void play(){ System.out.println("小狗喜欢玩皮球~"); }}
Copy after login

7 Extension

7.1 Design a comprehensive car case

Create package: cn.tedu.oopexec
Create class: DesignCar.java

package cn.tedu.oop2;/*本类用于完成汽车设计案例*/public class DesignCar { public static void main(String[] args) { //9.创建一个纯纯的父类对象进行测试 Car c = new Car(); System.out.println(c.getColor());//null c.start(); c.stop(); //c.swim();//报错,父类对象不可以调用子类的特有功能 //10.创建纯纯的子类对象做测试 BMW b = new BMW(); System.out.println(b.color);//五彩斑斓的黑 System.out.println(b.getColor());//null b.start();//都让开,我的车要起飞啦~ b.stop();//唉呀妈呀熄火了~ //11.创建多态对象进行测试 Car c2 = new TSL(); //System.out.println(c2.color); System.out.println(c2.getColor()); c2.stop(); c2.start(); //c2.swim(); }}//1.通过分析,抽象形成一个汽车类class Car{ //2.定义并封装汽车类的属性--成员变量 private String brand;//品牌 private String color;//颜色 private int id;//编号 private double price;//价格 //3.定义功能 public void start(){ System.out.println("我的小车车启动啦~"); } public void stop(){ System.out.println("唉呀妈呀熄火了~"); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }}//4.创建子类class BMW extends Car{ String color = "五彩斑斓的黑"; //5.重写父类的方法 @Override public void start(){ System.out.println("都让开,我的车要起飞啦~"); }}//6.创建子类2class TSL extends Car{ //7.重写父类的方法 @Override public void stop(){ System.out.println("唉呀妈,怎么停不下来呢"); } //8.添加子类的特有功能 public void swim(){ System.out.println("没想到吧,我还是个潜水艇"); }}
Copy after login

7.2 Polymorphism for unified calling standard

package cn.tedu.oop2;public class TestFruit { public static void main(String[] args) { Fruit f = new Fruit(); Apple a = new Apple(); Orange o = new Orange(); get(f); get(a); get(o); } //只需要创建一个方法,就可以执行截然不同的效果 //忽略子类对象的差异统一看作父类类型 public static void get(Fruit f){ f.clean(); }}class Fruit{ public void clean(){ System.out.println("水果要洗洗再吃"); }}class Apple extends Fruit{ @Override public void clean(){ System.out.println("苹果需要削皮"); }}class Orange extends Fruit{ @Override public void clean(){ System.out.println("橙子需要剥皮"); }}
Copy after login

7.3 The difference between static variables and instance variables

The difference in syntax definition: the static keyword must be added before static variables, but not before instance variables.
The difference when the program is running: Instance variables belong to the attributes of an object. An instance object must be created before the instance variable in it will be allocated space and this instance variable can be used. Static variables do not belong to an instance object, but to a class, so they are also called class variables. As long as the program loads the bytecode of the class without creating any instance objects, the static variables will be allocated space, and the static variables can be used. In short, instance variables must create an object before they can be used through this object, while static variables can be referenced directly using the class name.

7.4 Upward transformation and downward transformation

In JAVA, inheritance is an important feature. Through the extends keyword, subclasses can reuse the functions of the parent class. , if the parent class cannot meet the needs of the current subclass, the subclass can override the methods in the parent class to extend it.
Then there are polymorphic applications in this process. There are two ways of transformation: upward transformation and downward transformation.
Upward transformation: You can treat different subclass objects as parent classes, thereby shielding the differences between different subclass objects, writing common code, making common programming, and unifying calling standards.
For example: parent class Parent, subclass Child
The reference of the parent class points to the subclass object: Parent p=new Child();
Note: During upward transformation, the subclass object is regarded as the parent class object, only Can call the functions of the parent class. If the subclass overrides the method declared in the parent class, the method body executes the overridden function of the subclass. But at this time, the object regards itself as the parent type, so other resources still use the parent type.
For example: Hua Mulan joins the army for her father. Everyone regards Hua Mulan as her father, but it is Hua Mulan who actually joins the army. Moreover, Hua Mulan can only do what her father can do, and she is not allowed to wear makeup in the military camp. of.

Downcasting (less): The reference of the subclass points to the subclass object, and forced transformation must be adopted during the process. This is a subclass object that has been upwardly transformed before and still wants to perform the unique functions of the subclass, so it needs to be restored to a subclass object.
Parent p = new Child();//Upward transformation, at this time, p is the Parent type
Child c = (Child)p;//At this time, convert the Parent type p into the small type Child
In fact, it is equivalent to creating a subclass object. You can use the parent class or the My own
Note: When downward transformation is made, it is to facilitate the use of special methods of subclasses. That is to say, when the functions of subclass methods are expanded, the functions of subclasses can be used directly.
For example: After Hua Mulan’s war is over, she no longer needs to be regarded as her father, and can be "mirror decal yellow"

Recommended study: "java video tutorial"

The above is the detailed content of Master JAVA object-oriented polymorphism in one article. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!