Learning Java language from the beginning of the multi-state experience

Source: Internet
Author: User

First of all we have such a few classes, computers, personal computers, laptops.

class Computer{

  public void turnOn(){
  }
}

Now has the computer this class, then the personal PC, The notebook all is inherits him.

class PC extends Computer{
  public void turnOn(){
    System.out.println("PC has turn on");
  }
}

class NB extends Computer{
  public void turnOn(){
    System.out.println("NB has turn on");
  }
}

We see that each class has a turnon () method, and it may not be obvious here that the method is empty in the parent class and each has a different implementation in the subclass. If there is another way to accept these classes as arguments, just like this

class Test{
  public void go(Computer computer){
     computer.turnOn();
  }
}

This method receives the base class parameter, of course we can pass the class to the method, and should do so

go(new PC());
go(new NB());

So he's going to call the Turnon () method of the specific subclass, so the output of these two calls is not the same. If you do not use the base class as an argument, and we want to invoke the Turnon () method for each subclass, then we need some two method bodies like go () to receive the overloads of different parameters.

public void go(PC computer){
     computer.turnOn();
  }

public void go(NB computer){
     computer.turnOn();
  }

And that's right, but this will produce a lot of duplicate code, and is not easy to maintain, of course, this is only the most basic part of polymorphism, Java polymorphism Mechanism has a lot of features, about these suggestions to see the Java programming idea (think in Java) This book, which is very detailed, Here is a very simple description of a moment, but also hope that you do not laugh at the master.

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.