Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

java - What is the point of using abstract methods?

What's the point of using "abstract methods"? An abstract class cannot be instantiated, but what about the abstract methods? Are they just here to say "you have to implement me", and if we forget them, the compiler throws an error?

Does it mean something else? I also read something about "we don't have to rewrite the same code", but in the abstract class, we only "declare" the abstract method, so we will have to rewrite the code in the child class.

Can you help me understand it a bit more? I checked the other topics about "abstract class/methods" but I didn't find an answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Say you have a three printers that you would need to write a driver for, Lexmark, Canon, and HP.

All three printers will have the print() and getSystemResource() methods.

However, only print() will be different for each printer. getSystemResource() remains the same throughout the three printers. You also have another concern, you would like to apply polymorphism.

So since getSystemResource() is the same for all three printers, so this can be pushed up to the super class to be implemented, in Java, this can be done via making this abstract in the super class, and in making a method abstract in a super class, the class itself needs to be abstract as well.

public abstract class Printer{
  public void getSystemResource(){
     // real implementation of getting system resources
  }

  public abstract void print();
}

public class Canon extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to Canon
  }
}

public class HP extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to HP
  }
}

public class Lexmark extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to Lexmark
  }
}

Notice that HP, Canon and Lexmark classes do not provide the implementation of getSystemResource().

Finally, in your main class, you can do the following:

public static void main(String args[]){
  Printer printer = new HP();
  printer.getSystemResource();
  printer.print();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...