Abstract Classes

Abstract classes are a little like interfaces in that they are mainly used by class designers. They allow the creation of a class that cannot be instantiated itself but can be extended by a child class.

abstract class Person{
	public abstract String getName();
	public abstract String setName(String sName);
}

class Student extends Person{
	private String sPassword;
	public String getPassword(){
		return sPassword;
	}
	
	public void setPassword(String sPassword){
		this.sPassword=sPassword;
	}

}

Note how each method is marked as abstract as well as the class itself. Unlike an interface where no method has a body, methods in an abstract class can have a body. The following example shows an abstract class that has implemented methods.

abstract class Person{
	String sPhoneNumber;
	public abstract String getName();
	public abstract String setName(String sName);
	public void setPhoneNumber(String sPhoneNumber){
			this.sPhoneNumber = sPhoneNumber;
	}
	public String getPhoneNumber(){
		return sPhoneNumber;
	}
} 
Last modified: Sunday, 20 September 2015, 07:21 PM