Java Polymorphism Overview

Source: Internet
Author: User

Polymorphic

The so-called polymorphic, is actually a multi-state of an object;

In the following example, Tiger can be seen as Tiger, or as a animal

Cat can be seen as cat or animal

Dog can be seen as a dog, or as a animal.

Example code:

Package com.java1995;

Create a Animal class

public class Animal {
public void ShowMe () {
System.out.println ("I am an animal");
}

}

Package com.java1995;

Create a tiger class, inherit the animal class, and override its ShowMe () method

public class Tiger extends Animal {
public void ShowMe () {
System.out.println ("I Am a Tiger");
}

}

Package com.java1995;

Ibid., Cat class, inheriting animal class, overriding method

public class Cat extends Animal {
public void ShowMe () {
System.out.println ("I Am a cat");
//}

}

Package com.java1995;

Ibid., dog class, inheriting animal class, overriding method

public class Dog extends Animal {
public void ShowMe () {
System.out.println ("I am a Dog");
}

}

Package com.java1995;

Create a test class, play the Java language polymorphism, Tiger,cat,dog class

public class Test {
public static void Main (String [] args) {

Animal a=new Animal ();
A.showme ();

Two ways to create a tiger class
Tiger T=new Tiger (); First Kind
T.showme ();

Animal t2=new Tiger (); The second, Tiger belongs to the animal class, also belongs to the Tiger class
T2.showme ();

Animal c=new Cat ();
C.showme ();

Animal t3=new Tiger ();
ShowMe (T3);
TEST.SHOWME (t);

}

Create a showMe static method that integrates the above a.showme (); PS: Don't write
public static void ShowMe (Animal a) {
A.showme ();
}
}

Java Polymorphism Overview

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.