View RSS Feed

My Java Tips

Abstract Classes/Methods

Rate this Entry
by , 11-09-2011 at 04:58 PM (797 Views)
The 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.

Java Code:
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:

Java Code:
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

Submit "Abstract Classes/Methods" to Facebook Submit "Abstract Classes/Methods" to Digg Submit "Abstract Classes/Methods" to del.icio.us Submit "Abstract Classes/Methods" to StumbleUpon Submit "Abstract Classes/Methods" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments