Abstract keyword in Java

Posted on 03-01-2013 19:07 by graham
In this tutorial we will shortly discuss the abstract keyword commonly used in Java. The keyword can be applied to method or classes.

Abstract applied to class


When applied to a class, the abstract keyword means that the class cannot be instantiated. For example, if we want to make a class abstract, we use the following code:
public abstract class SomeClass
{
...
}

In this case it is impossible to create an instance of class SomeClass. Thus, the following code would not compile:
SomeClass obj = new SomeClass();

Only classes inheriting from SomeClass can be instantiated - if they are not abstract themselves.

Abstract applied to method


When applied to a method, the abstract keyword tells that we are only creating a signature of a given method with no implementation. E.g.
public abstract class SomeClass
{
// NOTE: the method has no body
public abstract void doSomething();
}

Note that the method doSomething above has no body - it will be implemented by any subclass that inherits from SomeClass. Also, note that SomeClass is itself abstract - this is because any class containing abstract methods must be also marked as abstract.

Now, if we want to inherit from SomeClass, we can either implement the abstract method doSomething(), or make our subclass abstract as well.
public class Subclass extends SomeClass
{
@Override
public void doSomething()
{
System.out.println("Hello from implemented method");
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems