Abstract
Abstract
Abstract classes may or may not contain abstract methods ie., methods with out
body ( public void get(); )
But, if a class have at least one abstract method, then the class must be
declared abstract.
To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the
abstract methods in it.
Example
This section provides you an example of the abstract class to create an abstract class
just use the abstract keyword before the class keyword, in the class declaration .
/* File name : Employee.java */
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
{
System.out.println("Inside Employee computePay");
return 0.0;
return name;
return address;
address = newAddress;
return number;
You can observe that except abstract methods the Employee class is same
as normal class in Java. The class is now abstract, but it still has three fields,
seven methods, and one constructor.
Now you can try to instantiate the Employee class as shown below:
e.mailCheck();
When you compile the above class, it gives you the following error:
1 error
salary)
setSalary(salary);
}
return salary;
salary = newSalary;
return salary/52;
Here, you cannot instantiate the Employee class, but you can instantiate the
Salary Class, and using this instance you can access the all the three fields
and seven methods of Employee class as shown below.
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
s.mailCheck();
e.mailCheck();
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
ailing check to Mohd Mohtashim with salary 3600.0
Abstract Methods:
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can
declare the method in the parent class as abstract.
You have to place the abstract keyword before the method name in the method
declaration.
Instead of curly braces an abstract method will have a semoi colon ( ; ) at the
end.
Below given is an example of the abstract method.
Any class inheriting the current class must either override the abstract method
or declare itself as abstract.
return salary/52;
}