Presentation is loading. Please wait.

Presentation is loading. Please wait.

Abstract Classes.

Similar presentations


Presentation on theme: "Abstract Classes."— Presentation transcript:

1 Abstract Classes

2 Abstract Classes As you move up inheritance hierarchy, more general and probably more abstract Instead of employee, student, parent  person Forms a basis for other classes Common attributes (such as name) Common methods (getDescription)

3 Abstract Methods getDescription
For student  a student majoring in math For employee  an employee with salary $50K Easy to implement for Student and Employee classes, but Person class? getDescription  empty string? Use abstract method public abstract String getDescription ( ); //no implementation required

4 Abstract Classes A class with one or more abstract methods must be declared to be abstract abstract class Person { … public abstract String getDescription ( ); } A class with no abstract methods may also be abstract

5 C++ Abstract Classes A class with one or more virtual methods is abstract class Person { … public: virtual string getDescription ( ) = 0; } No special keyword to denote abstract classes

6 Concrete data and methods
Can have concrete data and methods as well abstract class Person { public Person (String n) { name =n; } public abstract String getDescription ( ); public String getName ( ) { return name; private String name; You WANT to move as much functionality into superclass (whether or not it is abstract)

7 Instances Abstract classes cannot be instantiated, cannot create objects of that class new Person (“Vince Vahn”) Can create objects of concrete subclasses. Can create object variables of an abstract class, but it must refer to an object of nonabstract subclass! Person p = new Student (“Vince Vahn”, “Math”);

8 Extending Classes Two options
Leave some or all of abstract methods abstract (subclass is abstract) Define all methods

9 Example Class Student extends Person
{ public Student (String n, String m) { super (n); major = m; } public String getDescription ( ) //method defined { return “A student majoring in “ + major; private String major;

10 Invoking methods Person [ ] people = new Person [2];
People [0] = new Employee (…); People [1] = new Student ( …); Person p = people [i]; System.out.println (p.getName() + “, “ + p.getDescription());

11 Invoking methods Not a call to undefined method, p refers to object of concrete class, and it is defined for these classes Do NEED the abstract method to invoke!

12 The End


Download ppt "Abstract Classes."

Similar presentations


Ads by Google