Abstract methods and classes
Abstract method A placeholder for a method that will be fully defined in a subclass.
Abstract method An abstract method has a complete method heading with the addition of the keyword abstract. Cannot be private or final. Ex. abstract public double getPay ( ); abstract public void doSomething ( int count );
Abstract class A class that has at least one abstract method is called an abstract class. The class definition must have the keyword abstract. Ex. abstract public class Feet { … abstract void doSomething ( int count ); }
Abstract vs. concrete class A class without any abstract methods is called a concrete class.
Points to remember You cannot create an instance of an abstract class. Ex. Employee joe = new Employee(); //the above is illegal if Employee is abstract
Points to remember An abstract class is a type. Therefore you can use abstract classes as parameters to functions. Ex. (perfectly “legal”) public abstract class Employee { … public boolean samePay ( Employee other ) { }
public abstract class Employee { private String name; private Date hireDate; public abstract double getPay( ); public Employee( ) name = "No name"; hireDate = new Date("Jan", 1, 1000); //Just a place holder. } /** Precondition: Neither theName nor theDate are null. */ public Employee(String theName, Date theDate) if (theName == null || theDate == null) System.out.println("Fatal Error creating employee."); System.exit(0); name = theName; hireDate = new Date(theDate);
public Employee(Employee originalObject) { name = originalObject.name; hireDate = new Date(originalObject.hireDate); } public boolean samePay(Employee other) if (other == null) System.out.println("Error: null Employee object."); System.exit(0); //else return (this.getPay( ) == other.getPay( )); public String getName( ) return name; public Date getHireDate( ) return new Date(hireDate); ...
Points to remember An abstract class is a type. Therefore you can use abstract classes as variable types for concrete classes derived from the abstract class. Example follows…
Points to remember Ex. (perfectly “legal”) public abstract class Employee { … } public class HourlyEmployee extends Employee { public class SalaryEmployee extends Employee { Employee e = new HourlyEmployee();
Example Employee SalariedEmployee HourlyEmployee