It turns out that you are such a JAVA [03]-inheritance, polymorphism, abstract class, java Polymorphism

Source: Internet
Author: User
Tags define abstract

It turns out that you are such a JAVA [03]-inheritance, polymorphism, abstract class, java Polymorphism
1. Inheritance


In Java, the inheritance uses the keyword extends, which is slightly different from the C # syntax.

1. Subclass Constructor


Java will automatically insert a call to the parent class constructor In the constructor of the subclass. That is to say, the initialization of the parent class has been completed before the subclass can access the parent class.
To call the parent class constructor with parameters, useSuperKeyword.

/*** @ Author Chen Jing * @ date 18/1/17 */public class Product {private String name; public Product (String name) {this. name = name; System. out. println ("[Product constructor]") ;}} public class Bread extends Product {private int price; public Bread (String name, int price ){Super (name); // call the parent class ConstructorThis. price = price; System. out. println ("[Bread constructor]") ;}}

Let's create a Bread class instance to see the call sequence.

@ Testpublic void testConstructor () {Bread bread = new Bread ("caterpillar Bread", 10 );}

Print result:
[Product constructor]
[Bread constructor]

2. Call the parent class Method


Subclass cannot directly access the private domain of the parent class. If you want to access the private domain of the parent class, you can only use the get accesser exposed by the parent class. The subclass also needs to call the methods in the parent class.SuperKeyword.

public class Product {    private String name;    public String getName() {        return name;    }    public Product(String name) {        this.name = name;    }}public class Bread extends Product {    public Bread(String name) {        super(name);    }    public void display(){        System.out.println(getName());    }}

Then write a unit test:

@ Test public void testPrivate () {Bread bread = new Bread ("caterpillar bread"); Bread. display (); // caterpillar bread}

It should be noted that super is not an object reference and cannot assign super to a variable. It is just a special keyword that tells the editor to call methods in the parent class.

3. Reload


If the parent class contains an overloaded method and the Child class is overloaded, will the method in the parent class be overwritten? In fact, methods in the parent class and subclass can be reloaded without being overwritten.
First, add the method getDescription () to the parent Product ():

public class Product {     ……    public String getDescription() {         return "[Product]name="+name;     }}

Then, reload the method in the subclass:

public class Bread extends Product {     ……    public String getDescription(String storeName) {        return "[Bread]storename="+storeName;     }}

Add a unit test:

Public class ExtendClassTests {@ Test public void testOverload () {Bread bread = new Bread ("bean paste Bread", 9); System. out. println (bread. getDescription (); System. out. println (bread. getDescription (" "));}}

Output:
[Product] name = Bean Paste
[Bread] storename = meitu

4. Inheritance criteria


Inheritance principle: Use inheritance as little as possible. Generally, inheritance is used to express the differences between actions, and combinations are used to represent changes in the state.

2. Polymorphism

 

1. Variable Polymorphism


In Java, object variables are polymorphism. A Product variable can reference a Product object or a Product subclass object.

@Test
Public void testParent (){
Product product = new Bread ("caterpillar Bread", 10 );
Product. display ();

// Force type conversion
If (product instanceof Bread ){
Bread brand = (Bread) product;
Brand. display (" ");
}
}

Since the Bread instance is converted to the Product type upwards, you cannot call the Bread. getDescription (String storeName) method.
If you want to forcibly convert a parent class to a subclass, you must first use instanceof to detect the object type. We recommend that you avoid using forced type conversion.

2. dynamic binding


Dynamic binding is the method to be called at runtime Based on the object type. In java, dynamic binding is the default action and no additional keywords need to be added to implement polymorphism.

Write a demo and reload the display method in the parent class and subclass.

public class Product {     private String name;    public Product(String name) {         this.name = name;     }    public void display() {         System.out.println("[Product]getDescription()");     }}public class Bread extends Product {     private int price;    public Bread(String name, int price) {         super(name);         this.price = price;     }    @Override     public void display() {         System.out.println("[Bread]getDescription()");     }     public void display(String storeName) {         System.out.println("[Bread]getDescription(String storeName)");     }}

Add unit test:

@ Testpublic void dynamicBind () {Product product = new Product ("product"); product. display (); // [Product] getDescription () Bread bread = new Bread ("caterpillar", 9); bread. display (); // [Bread] getDescription () bread. display ("maimai"); // [Bread] getDescription (String storeName) Product product1 = bread; product1.display (); // [Bread] getDescription ()}

 

The virtual machine creates a method table for each class to list the signatures of all methods and actually called methods. In this way, when calling a method dynamically, you only need to find the method table to quickly find the actually called method.
Product:
Display ()-> Product. display ()
Bread:
Display ()-> Bread. display ()
Display (String name)-> Bread. display (String name)

Complete source code see: https://github.com/cathychen00/cathyjava/_ 08_extend

Iii. abstract classes

Abstract keywords are used to define abstract methods. They only have declarations but no method bodies.
Classes that contain abstract methods are called abstract classes. If a class contains one or more abstract methods, they must be defined as abstract classes.
If a class inherits from an abstract class, it must be implemented for all abstract methods in the abstract class. Otherwise, the class must be defined as an abstract class.
Let's look at a scenario: We have some scheduled tasks and the workflow is similar. Only a part of the details are different. We can define an abstract base class BaseJob and encapsulate different parts as abstract methods. The specific implementation is carried out in the subclass.

public abstract class BaseJob {     public void run(){         System.out.println("==START "+getDescription()+"==");         String lastJobId=getLastJobId();         execute(lastJobId);         writeLog();         System.out.println("==END "+getDescription()+"==");     }    protected abstract String getDescription();    protected abstract void execute(String jobId);    private void writeLog() {         System.out.println("write log to DB");     }    private String getLastJobId() {         return "job1221";     }}
Public class ArticleJob extends BaseJob {@ Override protected String getDescription () {return "Capture Article task" ;}@ Override protected void execute (String jobId) {System. out. println ("capture site news articles jobid =" + jobId);} public static void main (String [] args) {BaseJob articleJob = new ArticleJob (); articleJob. run ();}}

Create a unit test and call ArticleJob.

@Testpublic void articleJob(){     BaseJob articleJob=new ArticleJob();     articleJob.run();}

Running result:

= START crawling Article task = crawling site news articles jobid = job1221write log to DB = END crawling Article task =

When you add a scheduled task that meets the process again, you only need to create a new class to implement BaseJob.

Complete example: https://github.com/cathychen00/cathyjava/09_abstract

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.