Download presentation
Presentation is loading. Please wait.
1
Abstract methods and classes
2
Abstract method A placeholder for a method that will be fully defined in a subclass.
3
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 );
4
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 ); }
5
Abstract vs. concrete class
A class without any abstract methods is called a concrete class.
6
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
7
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 ) { }
8
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);
9
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); ...
10
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…
11
Points to remember Ex. (perfectly “legal”)
public abstract class Employee { … } public class HourlyEmployee extends Employee { public class SalaryEmployee extends Employee { Employee e = new HourlyEmployee();
12
Example Employee SalariedEmployee HourlyEmployee
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.