Abstract Class in Java
Abstract Class in Java
Create a super class that only defines a generalized form that will be shared by all of
its subclass leaving it to each subclass to fill in the details.
The key idea with an abstract class is useful when there is common functionality
that's like to implement in a super class and some behavior is unique to specific
classes.
So you implement the super class as an abstract class and define methods that have
common subclasses. Then you implement each subclass by extending the abstract
class and add the methods unique to the class.
Eg:
Courses
Start out with Courses super class, determine up front all the necessary and common
attributes needed by the class.
Some behaviors may be generic enough so that we can afford to program them in
detail for the Courses class, knowing that any sub classes of the Courses class will be
able to inherit these methods as it is without needing to override them.
A lecture course may meet only once a week for 3 hours at a time
A lab course may meet twice a week for 2 hours each time
An independent course may meet on a custom schedule that has jointly negotiated
by a given student & professor
syntax:
To declare abstract method
When we derive a class from an abstract super class, the sub clas will inherit all of the super
classs features, including the abstract methods.
To replace an inherited abstract method with a concrete version, the sub class needs to
merely override it; in doing so, we drop the abstract keyword from the method header and
replace the terminating semicolon with a method body, enclosed in braces.
Eg:
public class LectureCourse extends Courses
{
public void establishCourseSchedule(Strring startDate, String endDate)
{
/* Logic specific to the business rules for the LectureCourse
determine what day of the week the startDate falls on
determine how many weeks there are between startDate and the endDate;
schedule one 3hrs class meeting per week on the appropriate day of the
week
*/
}
}
public class Y
{
public void bar()
{
Concrete Logic;
}
public void foo()
{
Concrete Logic;
}
}
Program 1:
Program 2:
abstract class A
{
abstract void call();
void callme()
{
System.out.println("THIS IS AN NON-ABSTRACT METHOD");
}
}
class B extends A
{
void call()
{
System.out.println("IMPLEMENTING A's ABSTRACT METHOD ");
}
}
public class absDemo
{
public static void main(String args[])
{
B b=new B();
b.call();
b.callme();
}
}