29
CPSC150 Abstract Classes and Interfaces Chapter 10

CPSC150 Abstract Classes and Interfaces Chapter 10

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

CPSC150

Abstract Classes and Interfaces

Chapter 10

CPSC150

Directory Example(note: your assignment does not have a print method)

DirectoryEntrynamephone

public void print( ) { }

Sample Entry:StudentSusie Smith123 Main Street23 York River East(757) 234-6345Student

Home AddressSchool Address

public void print ( ) { }

subclass

superclass

subclass

subclass

superclass

CPSC150

DirectoryEntry print (note: your assignment does not have a print method)

public class DirectoryEntry {private String name;private String phone;

public void print( ) { System.out.println( “Name: “ + name +

“\nPhone: “ + phone); }

}

CPSC150

Student print (note: your assignment does not have a print method)

public class Student extends DirectoryEntry{private String homeAddress;private String schoolAddress;

public void print( ) { System.out.println(“Student: “ + “\nHome: “ + homeAddress + “\nSchool: “

+ schoolAddress); }}

CPSC150

Directory

public class Directory { ArrayList<DirectoryEntry> dir;// methods to create and fill dirpublic void print( ){

for (int i=0;i<dir.size();i++) {DirectoryEntry de = dir.get(i);

de.print( ); // will not work for assignment // will call subclass print only } }}

StudentHome: 123 Main StreetSchool: 23 York River East

no name!

CPSC150

Moral

• Java is polymorphic

• For syntax check, use parent class

• For runtime, child class will be called

• can’t get to parent class in client during runtime

CPSC150

Solution: fix Student print

private String homeAddress;private String schoolAddress;

public void print( ) { System.out.println( “Student: “ +

name + “\nPhone: “ + phone + “\nHome: “ + homeAddress + “\nSchool: “

+ schoolAddress); }

private access in parent;

can’t use

CPSC150

Solution Try #1 to Problem #2• call parent then childpublic void print( ) {

super.print( ); System.out.println(“Student: “ + “\nHome: “ + homeAddress + “\nSchool: “ + schoolAddress); }

– Problem now:print doesn’t look good

Susie SmithPhone: (757) 234-6345Student:Home: 123 Main StreetSchool: 23 York River East

CPSC150

Solution #2

• use protectedprotected String name; protected String phone– allows child access, but not others– solves the problem, but frowned on

• use accessor methods– works, but allows access that may not be

desired

• use protected accessor methods:

CPSC150

Solution: Protected access methods!

public class DirectoryEntry {private String name; private String phone;protected String getName( ) { return name; }protected String getPhone( ) {return phone; }

public class Student extends DirectoryEntry {//private instance fieldspublic void print( ) {

System.out.println( “Student: “ + super.getName( ) + “\nPhone: “ + super.getPhone( ) +

“\nHome: “ + homeAddress + “\nSchool: “ + schoolAddress); }

CPSC150

Now, DirectoryEntry print isn’t needed

• remove it (code not shown), but now: public class Directory { ArrayList<DirectoryEntry> dir;// methods to create and fill dirpublic void print( ){

for (int i=0;i<dir.size();i++) {DirectoryEntry de = dir.get(i);

de.print( ); }

// will cause syntax error if // DirectoryEntry has no print method

}}

CPSC150

Yet another problem

• Need print method for syntax checker

• Don’t need print method for runtime

• Solution: Leave it in there.

• Problem: Bad design

CPSC150

Final Solution: Abstract Methods

• Make print method abstract– means it cannot be called/used

• Leaves it there for compiler

• Shows that it will not be used for design

CPSC150

Abstract Classes

• If a method is abstract, it cannot be called• So, an object of that class can’t exist• So any class that has an abstract method MUST

be abstract

• Abstract classes can have any mix of concrete and abstract methods

• Concrete classes can be called by children objects of the class

CPSC150

Syntax of abstract methods

abstract public class MyClass{// regular constructors and methods that are

called in a regular way

abstract method signature ;//no body. NO {}s}

CPSC150

Why Abstract Methods

• Abstract Methods require any children to implement that method

• Compile time error if abstract method not in subclass

• Allow clients that use the code to compile with the guarantee that that method will be implemented

CPSC150

Your turn

• Write the abstract class DirectoryEntry. Make the print method abstract

Note: DirectoryEntry will NOT be abstract for your assignment

CPSC150

Inheritance ReviewNo different

than any other class.

Has no access to or information

about subclasses

class SubClass1

extends SuperClass

first line of constructor is

super( );

can use methods from SubClass1 or SuperClass

private in parent is not accessible

to children; protected is

Subclasses can have only one parent

CPSC150

Inheritance Review

Two reasons for inheritance

1. To use the methods of the parent

2. To use polymorphism (e.g. add DirectoryEntry to a directory, but each entry is a student, faculty or staff; directory doesn’t have to know which)

CPSC150

Abstract Classes Review

• Abstract methods enable polymorphism, but have no body

• Classes with abstract methods must be abstract

• Abstract classes can not have objects created from them

• Abstract classes can have useful concrete methods (e.g., getName) and fields (e.g.,name, phone)

CPSC150

Abstract Class Review

Two reasons for Abstract Classes

1. Enables polymorphism when methods are not appropriate for superclass (e.g., draw in Shapes or print in DirectoryEntry)

2. Enforces a specification (in order to be a DirectoryEntry, you must have a print method)

CPSC150

Interfaces

CPSC150

One more detail: Interfaces

• Allow multiple inheritance– Be an animal AND black (other things are

animals and other things are black)

• Can specify exactly what is needed for a concrete class– actionPerformed– Comparable

CPSC150

Interfaces

To implement

• in interface (parent), put:– public interface MyInterface

instead of

public class MyInterface

• in class using interface (child), put:– public class SubClass1 extends SuperClass implements MyInterface

CPSC150

Two arrow

s

Two arrow

s

CPSC150

Interfaces

• Just like a class, – but no variables (can have static final public

fields)– no bodies for ANY method

• Like abstract class on speed

• Purpose?– polymorphism– specification

CPSC150

Interface Example

• Comparable

CPSC150

Abstract Classes vs Interfaces

• Use interfaces when possible because there can lots of classes following "implements" but only one "extends"

• Use interfaces if you do not want any fields or methods in your parent class

• Use abstract classes if you want subclasses to use common defined methods or fields

CPSC150

• Look at the code below. You have five types (classes or interfaces) U, G, B, Z, and X, and a variable of each of these types. What can you say about the relationships of the types?

U u;G g;B b;Z z;X x;

Write the class/interface headers for U, G, Z and X

The following assignments are all legal:u = z;x = b;g = u;x = u;

The following assignments are all illegal (they cause compiler errors):u = b;x = g;b = u;z = u;g = x;