Java inheritance and polymorphism, java inheritance Polymorphism

Source: Internet
Author: User

Java inheritance and polymorphism, java inheritance Polymorphism
Parent class and subclass

If Class C1 is extended from another class C2, C1 is called a subclass or a derived class, and C2 is called a parent class or a base class. A derived class can inherit accessible data domains and methods from its base class, and can also add new data domains and methods.

For example, a base class of ry is implemented;

class GeometricObject1 {    private String color = "white";    private boolean filled;    private java.util.Date dateCreated;    public GeometricObject1() {        dateCreated = new java.util.Date();    }    public GeometricObject1(String color, boolean filled) {        dateCreated = new java.util.Date();        this.color = color;        this.filled = filled;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }    public boolean isFilled() {            return filled;    }    public void setFilled(boolean filled) {        this.filled = filled;    }    public java.util.Date getDateCreated() {        return dateCreated;    }    public String toString() {        return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled;    }}

A derived class Circle:

class Circle extends GeometricObject1 {    private double radius;        public Circle(double radius) {        this.radius = radius;    }    public Circle(double radius, String color, boolean filled) {        this.radius = radius;        setColor(color);        setFilled(filled);    }    public double getRadius() {        return radius;    }    public void setRadius(double radius) {        this.radius = radius;    }    public double getArea() {        return radius * radius * Math.PI;    }    public double getDiameter() {        return 2 * radius;    }    public double getPerimeter() {        return 2 * Math.PI * radius;    }    public void printCircle() {        System.out.println("The circle is creatd " + getDateCreated() +                " and the radius is " + radius);    }}

A derived class Rectangle:

class Rectangle extends GeometricObject1 {    private double width;    private double height;    public Rectangle() {            }    public Rectangle(double width, double height) {        this.height = height;        this.width = width;    }    public Rectangle(double width, double height, String color, boolean filled) {        this.width = width;        this.height = height;        setColor(color);        setFilled(filled);    }    public double getWidth() {        return width;    }    public void setWidth(double width) {        this.width = width;    }    public double getHeight() {        return height;    }    public void setHeight(double height) {        this.height = height;    }    public double getArea() {        return width * height;    }    public double getPerimeter() {        return 2 * (width + height);    }    }

Create a Circle and Rectangle object:

public class Main{    public static void main(String args[])    {        Circle circle = new Circle(1);        System.out.println("A circle " + circle.toString());        System.out.println("The radius is " + circle.getRadius());        System.out.println("The area is " + circle.getArea());        System.out.println("The diameter is " + circle.getDiameter());                Rectangle rectangle = new Rectangle(2, 4);        System.out.println("\nA rectangle " + rectangle.toString());        System.out.println("The area is " + rectangle.getArea());        System.out.println("The perimeter is " + rectangle.getPerimeter());            }}

Note:

1. The derived class is not a subset of the base class. In fact, it contains more information and methods than the parent class.

2. Private data domains in the parent class are not accessible outside of this class. If the parent class defines public accessors/modifiers, you can use these public accessors/modifiers to access and modify them.

3. Not all "yes" relationships (is-a) should be modeled using inheritance. For example, a square or a rectangle. If Class A is to be expanded using class B, A should contain more information than B.

4. Multi-inheritance is not allowed in java

Use the super keyword

Usage of the keyword super:

1. Call the constructor of the parent class

2. Call the method of the parent class

Syntax for calling the constructor of the parent class: super (), or super (parameters)

The super (), or super (parameters) statement must appear in the first row of the subclass constructor. This is the only way to explicitly call the parent constructor.

The constructor in the Circle class of the above Code can be replaced by the following code:

public Circle(double radius, String color, boolean filled) {    super(color, filled);    this.radius = radius;}

Super can reference not only the constructor of the parent class, but also the methods of the parent class:

Super. Method Name (parameter)

Rewrite the printCircle () method in the Circle class:

public void printCircle() {        System.out.println("The circle is creatd " + super.getDateCreated() +                " and the radius is " + radius);}
Overwrite Method

Subclass inherits methods from the parent class. Sometimes you need to modify the implementation of the methods defined in the parent class, which is called method overwrite.

The toString method in the GeometricObject class returns the string representing the geometric object. This method can be overwritten and returns a string that represents the circle. The following is a new method:

public String toString() {    return super.toString() + "\nradius is " + radius;}
Overwrite and reload

The overload method means that multiple methods with the same name can be defined, but these methods have different signatures. The overwrite method provides a completely new implementation for the methods in the subclass, this method has been defined in the parent class.

Example of overwriting:

Public class Main {public static void main (String args []) {A a = new A ();. p (10);. p (10.0) ;}} class B {public void p (double I) {System. out. println (I * 2);} class A extends B {public void p (double I) {// overwrite System. out. println (I );}}

Running result:

10.0
10.0

Example of heavy load:

Public class Main {public static void main (String args []) {A a = new A ();. p (10);. p (10.0) ;}} class B {public void p (double I) {System. out. println (I * 2);} class A extends B {public void p (int I) {// reload System. out. println (I );}}

Running result:

10
20.0

Polymorphism

You can pass the subclass instance to a parameter of the parent class type.

public class Main{    public static void main(String args[])    {        displayObject(new Circle(1, "red", false));        displayObject(new Rectangle(1, 1, "black", true));        }}public static void displayObject(GeometricObject object) {    System.out.println("Created on " + object.getDateCreated() +            ".Color is " + object.getColor());}

 

 


The Inheritance and Polymorphism in java are different.

Hey, here is an example that is easy to understand.
Hero: Li Qiming, Li Gang
Classic quotes: My father is Li Gang

Example:
According to Li Qiming, my father is Li Gang and has a scientific basis. Based on the Principle of program design, it conforms to the two major features of inheritance and polymorphism object-oriented programming.
Inheritance means that child classes can inherit the attributes and methods of the parent class. Private attributes and methods are included, but because private methods cannot be accessed, they are not inherited and are actually included in the subclass.
Public class Li Gang {
Private String rich;
Private String permission;
Private String;
Private String installation;
.............
... The corresponding get/set method ....

Public void love to drink (){
.......
}
............
}
These are some attributes and methods of Li Qiming's father Li Gang.
Public class Li Qiming extends Li Gang {
Private String 2;
Public void dare to drive into a car (){
.........
}
}
In Li Qiming, we do not seem to see the shadows of Li Gang. In fact, Li Gang's excellent genes have been inherited by Li Qiming. If you have an IDE development program, you can see that these methods are in Li Qiming. His son owns money, power, and arrogance!
But Li Qiming has some of his own characteristics, which Li Gang does not possess. For example, he dared to drive a car to hit a person, his dad couldn't do anything.
This means that child classes can be seen as parent classes, but they are not exactly the same, because child classes may have attributes and methods that the parent class does not have, that is, the son may do something that the father cannot do (that is, the special method in the subclass ).
Well, inheritance is almost the same. Let's take a look at polymorphism.
We still use this example.
Polymorphism: parent class references can hold subclass objects for more general programming.
The two classes above: Li Qiming and Li Gang
Now we have to instantiate these two items. (Terrible !)
Instantiate them separately:
Li Gang aa = new Li Gang ();
In this way, we can use some attributes of Li Gang.
Li Qiming bb = new Li Qiming ();
We can also use some methods from Li Qiming.
However, Li Qiming is an official second generation. Without Li Gang, nothing will happen. Therefore, in many cases, Li Qiming is the image of his father, Li Gang.
Li Gang cc = new Li Qiming ();
Hey, this is when we see Li Qiming. What we fear is not Li Qiming, but his father Li Gang. So we actually regard Li Qiming as Li Gang.
But there is a difference between Li Qiming and Li Gang. Li Qiming and Li Gang dare to hit people. This was the result of his father's cadre.
So when we do this, Li Gang cc = new Li Qiming ();
This cc object can only call methods in the parent class (Li Gang), because we regard it as a parent class.
If we want to know how many people Li Qiming has, or want to see how he dared to hit a person, we need to forcibly convert cc to Li Qiming class. To access those methods.
To sum up:
Inheritance: The subclass inherits the attributes and methods of the parent class. However, because this is the privacy of the parent class, the subclass inherits the attributes and methods of the private class, but there is no reference to these attributes and methods, so it is equivalent to not inherited. In many cases, it can be understood that there is no inheritance.
Polymorphism: parent class references can hold subclass objects. At this time, only methods in the parent class can be called, and special methods in the subclass cannot be accessed, because at this time (during compilation) you regard it as a parent class object, but when it comes to running, the compiler will ...... remaining full text>

How can we understand JAVA encapsulation, inheritance, and polymorphism?

Encapsulation, inheritance, and Polymorphism
Abstract: It is just a concept. You don't need to go too far when you first start learning. If you want to learn JAVA, you will understand these things, which is a little far-fetched, all you have to do is at least see the code to know what this is used.

The concept of encapsulation is better than that of a car. When you learn to drive, you only need to learn how to press the accelerator, brake, and turn the steering wheel. You do not need to know how the engine is started.

Inheritance: Let me first talk about my understanding of the class. The class has the following functions: Classification (the objects created by a class are actually the cases of this class) and the role of the template, inheritance plays a role in re-classification of classes. For example, there is a class of "Animals" and "mammals" that inherit "animals ", the next "horse" inherits the "Mammal" class. Here, from the bottom up, we first divide something into "horse" (of course, "Ox", "fish", and so on), and then we find that, there are many common features such as "horse" and "goat", so we once again divided the "Mammal" class, and again classified, we had "animals ". But in actual development, we generally define from the top down, that is, there are first "Animals", then "mammals", and finally "horses ".

Polymorphism, as my friend mentioned above, involves a heavy load. For example, the word "open" has different meanings at different times, such as "Open Door", "open window", and even "Drive ", "Open rice" and so on, with the same name but different operations. I will not go into detail about the specific implementation.

Let's talk about interfaces. JAVA does not support multi-inheritance. In fact, interfaces play a role similar to multi-inheritance. One class can only inherit from another class (or abstract class) but can implement multiple interfaces. For example, "Zhang San" is a "person", so he inherits "person". At the same time, he is a "driver ", his usual behavior is "Driving". Obviously, this cannot be inherited from the "person" class. What should I do? JAVA only supports single inheritance. At this time, the interface plays a role. It defines the "driver" interface and "Michael" implements it. Therefore, he will drive.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.