Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and when to use an abstract class

This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

Is it a mandatory or is it best method; if so how?

class Shape1 {     int i = 1;     void draw() {         System.out.println("this is shape:" + i);     } }  class Shape2 {     int i = 4;     void draw() {         System.out.println("this is shape2:" + i);     } }   class Shape {     public static void main(String args[]) {         Shape1 s1 = new Shape1();         s1.draw();          Shape2 s2 = new Shape2();         s2.draw();     } } 
like image 354
user568313 Avatar asked May 15 '11 07:05

user568313


People also ask

What is an abstract class and when do you use it?

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

Why should we use abstract class?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

When should we use abstract class in Java?

Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.

What is an abstract class and why might you use one?

Declaring a class as abstract means that it cannot be directly instantiated, which means that an object cannot be created from it. That protects the code from being used incorrectly. Abstract classes require subclasses to further define attributes necessary for individual instantiation.


1 Answers

You'd use an abstract class or interface here in order to make a common base class/interface that provides the void draw() method, e.g.

abstract class Shape() {   void draw(); }  class Circle extends Shape {    void draw() { ... } }  ...  Shape s = new Circle(); s.draw(); 

I'd generally use an interface. However you might use an abstract class if:

  1. You need/want to provide common functionality or class members (e.g. the int i member in your case).
  2. Your abstract methods have anything other than public access (which is the only access type allowed for interfaces), e.g. in my example, void draw() would have package visibility.
like image 62
Thomas Avatar answered Sep 23 '22 13:09

Thomas