What is an abstract method and how to use it?

Posted Jul 14, 2009 by AmanDhiman / comments 0 comments / Print / Font Size Decrease font size Increase font size

Introduction to an abstract method and information on how we can use it correctly?

An abstract method is special kind of method that we call as a unimplemented method. An abstract method can only be written inside an abstract class. This is a method which has no {} braces and no statements. It is just declared and we type a semicolon ; at the end of this type of method. We use this type of method in a very rare situations, especially when we want a method to be overridden and have no body itself. For example,

abstract class Example

{

// A normal method.

public void method1()

{
}

// An abstract method with no body.

public abstract void method2();

}

class MyClass extends Example

{

public void method2()

{

// This method will have to be overridden else a compile - time error will be thrown.

}

public static void main(String[] args)

{
}

}

In the above example we have a class named as Example and we have declared two methods in side it namely, method1() and method2(). The first method, which is method1(), is a normal method but the second method, which is method2(), is an abstract method. An abstract method has to be overridden in the class that extends the class, in which the abstract method is declared. Then we have created a class named as MyClass and we have overridden the method2() function and we have created the main() method in this class and this means that when the program execution starts that will first of all enter this method and this method is called the entry point of the program because this is the method that starts first of all.

Rate this Article:

Be the first to rate me.

  • Nothing Found!

    Why not submit your own content? Signup here.


* You must be logged in order to leave comments, please login or join us.

Comments

No comments yet.



Bookmark and Share
Sign up for our email newsletter
Name:
Email: