Javase Getting Started learning 18:java object-oriented polymorphism

Source: Internet
Author: User

one Java polymorphic

Polymorphism is the ability of the same behavior to have many different manifestations or forms.

Polymorphism is the embodiment of multiple forms of objects. For example, we say, "Pet

Object ". It has many different expressions or implementations, such as kittens, puppies, lizards, and so on. So I went to the pet store and said, "Please give me a pet."

The waiter gave me a kitten, a puppy or a lizard, and we said, "pet," the object is polymorphic.

Let's take a look at Java polymorphism by example.

Example:

Vegetarian.java Source file Code:

<span style= "FONT-SIZE:18PX;" >public interface vegetarian{       //implementation Details}</span>

Animal.java Source file Code:

<span style= "FONT-SIZE:18PX;" >public class animal{      //implementation Details}</span>

Deer.java Source file Code:

<span style= "FONT-SIZE:18PX;" >public class Deer extends Animal implements vegetarian{        //implementation Details}</span>

Because the deer class has multiple inheritance. So it is polymorphic. The above examples are parsed for example:

A Deer is-a (is a) Animal

A Deer is-a (is a) vegetarian

A Deer is-a (is a) Deer

A Deer is-a (is a) Object

In Java, all objects are polymorphic, because no matter what object can pass the IS-A test type and object class.

This can be used in the back.

Instanceofkeyword to verify.

The only way to access an object is through a reference variable. A reference variable can only have one type once it is declared. The type of the reference variable is

cannot be changed. Reference variables can be reset not only to other objects, but only if the objects are not declared final.

It is also possible to reference the type

The same or compatible object.

It can be declared as a class type or an interface type.

When we apply a reference variable to a reference to a Deer object, the following declaration is valid:

Deer d = new Deer ();

Animal a = D;

Vegetarian v = d;

Object o = D;

All reference variable d,a,v,o points to the same deer object in the heap.

Two virtual methods

When designing a class in Java, how the behavior of the overloaded method affects polymorphism. We have discussed the overloading of methods, that is, subclasses can overload

The method of the parent class. When a subclass object calls an overloaded method, the method of the child class is called, not the overloaded method in the parent class.

To invoke a method that is overloaded in the parent class. You must use Keywordsuper.


Instance:

Employee.java Source file Code:

<span style= "FONT-SIZE:18PX;"        >public class employee{//Private member variable private String name;        Private String address; private int number;//Constructor public Employee (string name, string address, int number) {System.out.print                ln ("Constructing an Employee");                THIS.name = name;                this.address = address;        This.number = number; } public void MailCheck () {System.out.println ("mailing a check to" + THIS.name + "" + this.address)        ;        } public String toString () {return name + "+ address +" "+ number;        } public String GetName () {return name;        } public String getaddress () {return address;        } public void Setaddress (String newaddress) {address = newaddress;        } public int GetNumber () {return number; }}</span>

If the following salary class inherits the employee class:

Salary.java source file code:
<span style= "FONT-SIZE:18PX;" >public class Salary extends employee{//Private member variable private double Salary;//annual Salary//constructor public Salary (String name, address string, int number, double salary)           {//Inherit member variables of parent class employee class super (name, address, number);    Setsalary (Salary); }//Overrides the MailCheck () method of the parent class employee class public void MailCheck () {System.out.println ("within MailCheck of Salary CLA          SS ");    System.out.println ("Mailing Check to" + getName () + "with salary" + salary);    } public double Getsalary () {return salary;          public void Setsalary (double newsalary) {if (newsalary >= 0.0) {salary = Newsalary; }}//Subclass salary Class unique Computepay () method public double Computepay () {System.out.println ("Computing Salary pay          For "+ getName ());    return SALARY/52; }}</span>
Now we read the following code carefully. Give the output of the result:
Virtualdemo.java Source file Code:
<span style= "FONT-SIZE:18PX;" >public class virtualdemo{public    static void Main (string[] args) {        //Instantiate object S of salary class (reference to object of this class)        Salary s = new Salary ("Mohd Mohtashim", "Ambehta, Up", 3, 3600.00);//Instantiate an Employee Class object E (the parent class's reference to the object of the subclass)        Employee e = new S Alary ("John Adams", "Boston, MA", 2, 2400.00);        System.out.println ("Call MailCheck using Salary reference-");//When creating this class object. The method called is S.mailcheck () of this class method        ;        System.out.println ("\ n call MailCheck using Employee reference--");//When you create a subclass object, the method that is called is the method that the subclass overrides or the inherited method        E.mailcheck () ;    }} </span>
The above example compiles execution results such as the following:

Example Explanation:

In the sample, we instantiate two salary objects.

One uses this class salary class reference S. There is also an employee class reference that uses the parent class.

At compile time, the compiler checks the declaration of the MailCheck () method in the salary class.

When S.mailcheck () is called. Java Machine (JVM) Call salary

The MailCheck () method of the class. Because E is a reference to employee. So the Emailcheck () method of the call has a completely different result.

When the compiler examines the E.mailcheck () method, the compiler examines the MailCheck () method in the Employee class. At compile time, the compiler makes

The statement is validated with the MailCheck () method in the employee class, but at execution time, the Java Virtual machine (JVM) calls the salary class.

MailCheck () method. This behavior is called a virtual method call, and the method is called a virtual method.

All of the methods in Java can behave in this way, so that the overridden method can be invoked at execution time, regardless of the source code referenced in the compilation.

is what data type.

Three object-oriented multi-state summarization

1 referencing polymorphism

References to this class can point to objects of this class.

A reference to the parent class can point to the object of the subclass.

2 Method polymorphism

When you create this class object. The method that is called is the method of this class.

When you create a subclass object, the method that is called is the method that the subclass overrides or the inherited method.

Four conversion of reference types in polymorphic Let's take a look at the example:
Animal.java Source file Code:
<span style= "FONT-SIZE:18PX;" >public class animal{public String name;public int age;public Animal () {System.out.println ("I am the constructor of the Animal class");}} </span>
Dog.java source file code:
<span style= "FONT-SIZE:18PX;" >public class Dog extends Animal{public dog () {System.out.println ("I am the constructor of the Dog class");}} </span>
Test.java source file code:
<span style= "FONT-SIZE:18PX;" >public class test{public   static void Main (string[] args) {         //Instantiate Animal class  Animal a1 = new Animal ();// The parent class refers to an object of this class  Animal a2 = new Dog ();//The reference to the parent class to the object of the subclass    //instantiation of the Dog class  dog D1 = new Dog ();//Sub-class object to this class  Dog d2 = new Ani Mal ();//Sub-class to the parent class object. This compilation will fail   }}</span>
Compilation Result:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

We can use the instanceof operator to determine the type of the object:

overwrite Test.java source file code:
<span style= "FONT-SIZE:18PX;" >public class test{public   static void Main (string[] args) {          //Instantiate Animal class  Animal a1 = new Animal ();// The parent class refers to an object of this class  Animal a2 = new Dog ();//The reference to the parent class to the object of the subclass    //instantiation of the Dog class  dog D1 = new Dog ();//Sub-class object to this class  //dog d2 = new A Nimal ();//Sub-class to the parent class object. This compilation will fail    System.out.println (A1 instanceof Animal);  SYSTEM.OUT.PRINTLN (A2 instanceof Animal);  System.out.println (D1 instanceof Dog);}   } </span>
Execution Result:
Summary of five reference type conversions

1) Up-type conversions (implicit or self-active type conversions), are small types to large types of conversions. There is no security issue.

2) downward type conversion (coercion type conversion), is a large type to a small type of conversion. There is a security issue. Overflow of data.

3) The instanceof operator to determine the type of reference object and to avoid the security of type conversions.



Javase Getting Started learning 18:java object-oriented polymorphism

Related Article

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.