Abstract class in Java

205,322

Solution 1

An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:

  1. Define methods which can be used by the inheriting subclass.
  2. Define abstract methods which the inheriting subclass must implement.
  3. Provide a common interface which allows the subclass to be interchanged with all other subclasses.

Here's an example:

abstract public class AbstractClass
{
    abstract public void abstractMethod();
    public void implementedMethod() { System.out.print("implementedMethod()"); }
    final public void finalMethod() { System.out.print("finalMethod()"); }
}

Notice that "abstractMethod()" doesn't have any method body. Because of this, you can't do the following:

public class ImplementingClass extends AbstractClass
{
    // ERROR!
}

There's no method that implements abstractMethod()! So there's no way for the JVM to know what it's supposed to do when it gets something like new ImplementingClass().abstractMethod().

Here's a correct ImplementingClass.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
}

Notice that you don't have to define implementedMethod() or finalMethod(). They were already defined by AbstractClass.

Here's another correct ImplementingClass.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
}

In this case, you have overridden implementedMethod().

However, because of the final keyword, the following is not possible.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
    public void finalMethod() { System.out.print("ERROR!"); }
}

You can't do this because the implementation of finalMethod() in AbstractClass is marked as the final implementation of finalMethod(): no other implementations will be allowed, ever.

Now you can also implement an abstract class twice:

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
}

// In a separate file.
public class SecondImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("second abstractMethod()"); }
}

Now somewhere you could write another method.

public tryItOut()
{
    ImplementingClass a = new ImplementingClass();
    AbstractClass b = new ImplementingClass();

    a.abstractMethod();    // prints "abstractMethod()"
    a.implementedMethod(); // prints "Overridden!"     <-- same
    a.finalMethod();       // prints "finalMethod()"

    b.abstractMethod();    // prints "abstractMethod()"
    b.implementedMethod(); // prints "Overridden!"     <-- same
    b.finalMethod();       // prints "finalMethod()"

    SecondImplementingClass c = new SecondImplementingClass();
    AbstractClass d = new SecondImplementingClass();

    c.abstractMethod();    // prints "second abstractMethod()"
    c.implementedMethod(); // prints "implementedMethod()"
    c.finalMethod();       // prints "finalMethod()"

    d.abstractMethod();    // prints "second abstractMethod()"
    d.implementedMethod(); // prints "implementedMethod()"
    d.finalMethod();       // prints "finalMethod()"
}

Notice that even though we declared b an AbstractClass type, it displays "Overriden!". This is because the object we instantiated was actually an ImplementingClass, whose implementedMethod() is of course overridden. (You may have seen this referred to as polymorphism.)

If we wish to access a member specific to a particular subclass, we must cast down to that subclass first:

// Say ImplementingClass also contains uniqueMethod()
// To access it, we use a cast to tell the runtime which type the object is
AbstractClass b = new ImplementingClass();
((ImplementingClass)b).uniqueMethod();

Lastly, you cannot do the following:

public class ImplementingClass extends AbstractClass, SomeOtherAbstractClass
{
    ... // implementation
}

Only one class can be extended at a time. If you need to extend multiple classes, they have to be interfaces. You can do this:

public class ImplementingClass extends AbstractClass implements InterfaceA, InterfaceB
{
    ... // implementation
}

Here's an example interface:

interface InterfaceA
{
    void interfaceMethod();
}

This is basically the same as:

abstract public class InterfaceA
{
    abstract public void interfaceMethod();
}

The only difference is that the second way doesn't let the compiler know that it's actually an interface. This can be useful if you want people to only implement your interface and no others. However, as a general beginner rule of thumb, if your abstract class only has abstract methods, you should probably make it an interface.

The following is illegal:

interface InterfaceB
{
    void interfaceMethod() { System.out.print("ERROR!"); }
}

You cannot implement methods in an interface. This means that if you implement two different interfaces, the different methods in those interfaces can't collide. Since all the methods in an interface are abstract, you have to implement the method, and since your method is the only implementation in the inheritance tree, the compiler knows that it has to use your method.

Solution 2

A Java class becomes abstract under the following conditions:

1. At least one of the methods is marked as abstract:

public abstract void myMethod()

In that case the compiler forces you to mark the whole class as abstract.

2. The class is marked as abstract:

abstract class MyClass

As already said: If you have an abstract method the compiler forces you to mark the whole class as abstract. But even if you don't have any abstract method you can still mark the class as abstract.

Common use:

A common use of abstract classes is to provide an outline of a class similar like an interface does. But unlike an interface it can already provide functionality, i.e. some parts of the class are implemented and some parts are just outlined with a method declaration. ("abstract")

An abstract class cannot be instantiated, but you can create a concrete class based on an abstract class, which then can be instantiated. To do so you have to inherit from the abstract class and override the abstract methods, i.e. implement them.

Solution 3

A class that is declared using the abstract keyword is known as abstract class. Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

Main things of abstract class

  • An abstract class may or may not contain abstract methods.There can be non abstract methods.

    An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

    ex : abstract void moveTo(double deltaX, double deltaY);

  • If a class has at least one abstract method then that class must be abstract

  • Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)

  • To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.

  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Declare abstract class Specifying abstract keyword before the class during declaration makes it abstract. Have a look at the code below:

abstract class AbstractDemo{ }

Declare abstract method Specifying abstract keyword before the method during declaration makes it abstract. Have a look at the code below,

abstract void moveTo();//no body

Why we need to abstract classes

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.

This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject) as shown in the following figure. enter image description here

First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:

abstract class GraphicObject {

  void moveTo(int x, int y) {
    // Inside this method we have to change the position of the graphic 
    // object according to x,y     
    // This is the same in every GraphicObject. Then we can implement here. 
  }

  abstract void draw(); // But every GraphicObject drawing case is 
                        // unique, not common. Then we have to create that 
                        // case inside each class. Then create these    
                        // methods as abstract 
  abstract void resize();
}

Usage of abstract method in sub classes Each non abstract subclasses of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods.

class Circle extends GraphicObject {
  void draw() {
    //Add to some implementation here
  }
  void resize() {
    //Add to some implementation here   
  }
}
class Rectangle extends GraphicObject {
  void draw() {
    //Add to some implementation here
  }
  void resize() {
    //Add to some implementation here
  }
}

Inside the main method you can call all methods like this:

public static void main(String args[]){
   GraphicObject c = new Circle();
   c.draw();
   c.resize();
   c.moveTo(4,5);   
}

Ways to achieve abstraction in Java

There are two ways to achieve abstraction in java

  • Abstract class (0 to 100%)
  • Interface (100%)

Abstract class with constructors, data members, methods, etc

abstract class GraphicObject {

  GraphicObject (){
    System.out.println("GraphicObject  is created");
  }
  void moveTo(int y, int x) {
       System.out.println("Change position according to "+ x+ " and " + y);
  }
  abstract void draw();
}

class Circle extends GraphicObject {
  void draw() {
    System.out.println("Draw the Circle");
  }
}

class TestAbstract {  
 public static void main(String args[]){

   GraphicObject  grObj = new Circle ();
   grObj.draw();
   grObj.moveTo(4,6);
 }
}

Output:

GraphicObject  is created
Draw the Circle
Change position according to 6 and 4

Remember two rules:

  • If the class has few abstract methods and few concrete methods, declare it as an abstract class.

  • If the class has only abstract methods, declare it as an interface.

References:

Solution 4

It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.

Solution 5

Get your answers here:

Abstract class vs Interface in Java

Can an abstract class have a final method?

BTW - those are question you asked recently. Think about a new question to build up reputation...

Edit:

Just realized, that the posters of this and the referenced questions have the same or at least similiar name but the user-id is always different. So either, there's a technical problem, that keyur has problems logging in again and finding the answers to his questions or this is a sort of game to entertain the SO community ;)

Share:
205,322

Related videos on Youtube

Ravindra babu
Author by

Ravindra babu

A competent professional with 20 years of experience in: ~ Product Development ~ Enterprise Architecture ~ Sustained Engineering ~ B2B/B2G Integration ~ Machine learning ~ Team Management ~ Delivery Management ~ Project Management ~ Risk Management

Updated on May 17, 2020

Comments

  • Ravindra babu
    Ravindra babu almost 4 years

    What is an "abstract class" in Java?

    • Yuval
      Yuval over 14 years
      +1 This question is so basic and fundamental, it's a classic for SO. I'm surprised it hasn't been asked here before.
    • Jonik
      Jonik over 14 years
      -1 for Clement's comment (if I could); lmgtfy is not a helpful reply. As for why, read e.g. this meta.stackexchange.com/questions/5280/embrace-the-non-google‌​rs
    • tuergeist
      tuergeist over 14 years
      The result is too easy to google and it's even a language basic. I totaly agree with Clement.
    • Jonik
      Jonik over 14 years
      @tuergeist. It's irrelevant if it's easy to Google, as long as it hasn't been asked on SO before. Also, who says beginner questions about programming languages don't belong on SO?
    • Anders Hansson
      Anders Hansson over 14 years
      One thing I like about SO is that you would get an answer that is condensed, well put and to the point without any of the usual BS found on the rest of the web... Well, something like that anyway. +1 for the question!
    • kwutchak
      kwutchak over 14 years
      SO isn't just supposed to have the long tail! J&J even talk about this around podcast 56...
    • Andreas Dolk
      Andreas Dolk over 14 years
      a virtual -1 because at least four nearly similar questions have been asked by four different (abstract?) keyur's before.
    • Jonik
      Jonik over 14 years
      @Andreas, interesting; can you give examples? (I couldn't find any such questions google.fi/#q=keyur+site:stackoverflow.com)
    • Andreas Dolk
      Andreas Dolk over 14 years
      @Jonik - look at my 'answer' I put to this question. The links are included
    • Jonik
      Jonik over 14 years
      @Andreas - ah, indeed (Google hadn't indexed those yet)
    • Ravindra babu
      Ravindra babu about 8 years
      stackoverflow.com/questions/13824142/… has been linked to this question. So this question should contain information about abstract methods too
  • Stephen C
    Stephen C over 14 years
    Nitpick: the second 'condition' is redundant, since you can only declare an abstract method in a class that is explicitly declared as abstract.
  • Imagist
    Imagist over 14 years
    This answer isn't helpful if the OP doesn't know what an interface is. Since abstract classes and interfaces are interrelated, it's highly unlikely that the OP would know one without knowing the other.
  • Noon Silk
    Noon Silk over 14 years
    Agreed, the advice is not really correct, or well written, it's just formatted nicely.
  • Noon Silk
    Noon Silk over 14 years
    But your advice 'to make a class concrete' is worded wrong as well. You don't make a class concrete, it either is, or isn't, depending on if it's abstract or not.
  • Daniel Rikowski
    Daniel Rikowski over 14 years
    doh, not enough caffeine yet. Updated again, thank's for the hint.
  • NomeN
    NomeN over 14 years
    try formatting all code as code, and please add some explanation, right now this can hardly be considered an answer.
  • abhijeet nigoskar
    abhijeet nigoskar over 14 years
    But it could be. It could be that he just knows what an interface is and how it works, and then he comes across abstract classes and wonders why one should need them. Couldn't that be?
  • Jorn
    Jorn over 14 years
    This is just plain wrong. An abstract class doesn't have to have any abstract methods. You can make an abstract class without methods, or with only concrete methods.
  • Daniel Rikowski
    Daniel Rikowski over 14 years
    I'm not sure I understand what you are saying. I never wrote something like that, not even in the less-then-perfect first versions. On the contrary: I explicitly state what you are saying: "But even if you don't have any abstract method you can still mark a class as abstract."
  • Andreas Dolk
    Andreas Dolk over 14 years
    And that's why I checked 'community wiki' - one shouldn't increase reputiation through reacting on those questions ;)
  • devsda
    devsda over 11 years
    until and unless you didn't give explanation of your code. You would be considered as a bad answer maker. So please give explanation here
  • Sachin Kumar
    Sachin Kumar about 9 years
    @Imagist -1 for wrong description for the statement c.implementedMethod(); // prints "implementedMethod()", It will print "Overriden!" always
  • Rounak
    Rounak about 9 years
    @Sachin I wasted half an hour tyring to understand why it would print "implementedMethod()" and then I saw your comment. Did something change with java or did others just overlooked the mistake?
  • Mateen Ulhaq
    Mateen Ulhaq over 8 years
    @SachinKumar Due to the author's lack of response, I have taken it upon myself to fix this error. CMIIW.
  • Schwaitz
    Schwaitz about 7 years
    @SachinKumar I'm a bit late to the game here, but would you say that a good analogy would be to a method declaration (but no implementation) in a C++ header file?
  • John Red
    John Red about 7 years
    @SachinKumar why would c.implementedMethod() print "Overriden!"? SecondImplementingClass does not override implementedMethod().
  • Jonathan Rys
    Jonathan Rys about 6 years
    Why is the order of the parameters x and y in moveTo different in the in the example above, the example below, and the output from the example below? If we're trying to illustrate the importance of concepts like interfaces and abstract classes, shouldn't we use the same function signatures as the interfaces or abstract classes we're implementing or extending consistently?
  • Rakib
    Rakib about 5 years
    10 years late to the game, but this is the most precise answer. @Jorn you are confused with the answer I think. I'm sure it is implied that abstract keyword is all that is necessary for a class to be abstract. But A concrete class cannot contain an abstract method. Thus if your class has an abstract method, it has to be declared as an abstract class to the compiler.
  • LiNKeR
    LiNKeR over 4 years
    the two rules give it away