What are Abstract Classes and Mehods in java?

Before jumping into the Abstract Classes we need to know what Abstraction is. Abstraction is the process of hiding the details of the process of implementation and only showing the functional part only to the user.

A class declared with abstract keyword in java is called abstract class. An Abstract class can have both abstract and non abstract methods but you are not allowed to create the object of abstract class.

Similarly, an Abstract method has no body and always end the declaration with a semicolon(;). It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden. In the example given below the class Place is the abstract class.


abstract class Place{

String name;
String description;

public Place(String name){
this.name=name;
}

public String getName(){
return name;
}

public abstract String getDescription();

}

class Districts extends Place{
private String headquarter;
public Districts(String name, String hq){
super(name);
this.headquarter=hq;
}
public String getHeadquarterName(){
return headquarter;
}
public String getDescription(){
return "The headquarter is "+headquarter;
}

}

class Municipality extends Place{
private int wards;
public Municipality(String name, int w){
super(name);
this.wards = w;
}

public int getNoOfWards(){
return wards;
}

public String getDescription(){
return "The number of wards is: "+wards;
}

}

 

public class AbstractEg {
public static void main(String[] args){

Place[] place = new Place[2];

place[0] = new Districts("Dang ","Ghorahi");
place[1] = new Municipality("Tulsipur Municipality ",19);

for(int i=0; i<place.length; i++){
Place p = place[i];
System.out.println(p.getName()+""+p.getDescription());
}

}

}

Output:

Dang The headquarter is Ghorahi
Tulsipur Municipality The number of wards is: 19

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s