Abstract Classes/Methods
27 November 2007The keyword abstract is used when a class is declared abstract. An abstract may or may not include abstract methods. These classes can be inherited (subclasses) but cannot be instantiated.
Abstract classes comprise of concrete methods and abstract methods. Concrete methods are methods with body and abstract methods are without body methods. The class implementing the abstract class has to override abstract methods.
Abstract methods are without implementation (without braces) and they are followed by a semicolon.
abstract void myMethod(double x, double y);
Many new programmer mix interfaces with abstract classes. Interfaces comprise of constants and abstract methods. The methods don’t have body and thus doesn’t have default behavior. On the other hand, abstract classes have methods with body and without body. Methods with body provide default behavior and they can also be overridden in the child class but the child class has to override the abstract methods (methods without body).
Review the example below:
public abstract class MyAbstractClass { public String getWelcomeMsg(){ return "Good Morning"; } public abstract String getStatus(); } public class MyClass extends MyAbstractClass { public String getStatus() { return "Started"; } public static void main(String[] args) { MyClass obj = new MyClass(); System.out.println(obj.getWelcomeMsg()); System.out.println(obj.getStatus()); } }
Output:
Good Morning Started
If abstract method in the example above is not overridden, the compiler with show the following error message:
The method main(String[]) of type MyClass must override a super class method
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Abstract Classes/Methods