0% found this document useful (0 votes)
50 views9 pages

Chapter 5 Class Hierarchies and Interfaces

This document discusses Java class hierarchies and inheritance. It covers key concepts such as: 1) Subclasses inherit fields and methods from superclasses but not constructors. 2) Abstract classes serve as common superclasses and define abstract methods that subclasses must implement. 3) Polymorphism allows calling methods for an object based on its type, so code works for subclasses.

Uploaded by

mako Kkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views9 pages

Chapter 5 Class Hierarchies and Interfaces

This document discusses Java class hierarchies and inheritance. It covers key concepts such as: 1) Subclasses inherit fields and methods from superclasses but not constructors. 2) Abstract classes serve as common superclasses and define abstract methods that subclasses must implement. 3) Polymorphism allows calling methods for an object based on its type, so code works for subclasses.

Uploaded by

mako Kkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

M.

El Dick

Inheritance
 A subclass inherits all the fields and methods of
its superclass, but not constructors

Superclass
CLASS (Base class)
Subclass extends
HIERARCHIES AND Superclass

INTERFACES Subclass
(Derived class)

Chapter 5 M. El Dick

Java Hierarchy Class Hierarchies


 Using inheritance, a programmer can define a
hierarchy of classes
Biped

Walker Hopper Dancer

ToeWalker CharlieChaplin

M. El Dick M. El Dick
Advantages of Class Hierarchies Factoring out Common Code
 Reduce duplication of code by : Biped
 Factoring out common code from similar classes into a Constructor
common superclass turnLeft
turnRight
 Writing more general methods turnAround

Walker Hopper
Constructor Constructor
firstStep() firstStep()
nextStep() nextStep()
stop() stop()
distanceTraveled() distanceTraveled()
M. El Dick M. El Dick

Writing General Methods Polymorphism


public void moveAcross public void moveAcross
(Walker creature, int distance) (Biped creature, int distance) Method is called for an object based on its type
{ {
creature.firstStep(); creature.firstStep();  Once you define a common superclass, polymorphism is
while (creature.distanceTraveled() < distance) while (creature.distanceTraveled() <
creature.nextStep();
distance) just there  no need to do anything special
creature.stop();
}
creature.nextStep();
creature.stop();
public void moveAcross }
(Hopper creature, int distance)
{
creature.firstStep(); Works for either
while (creature.distanceTraveled() < distance) Walker or Hopper
creature.nextStep();
creature.stop(); due to polymorphism
}

M. El Dick M. El Dick
Parameter can be a Walker, a
Hopper, etc.  any subclass of Biped. Abstract Class
 Some methods in a class can be declared abstract and left with
public void moveAcross (Biped creature, int distance) only signatures defined
{
creature.firstStep();
A class with one or more public abstract class Biped
while (creature.distanceTraveled () < distance)
abstract methods must be {
creature.nextStep();
declared abstract ...
creature.stop();
public abstract void firstStep();
}
public abstract void nextStep(); Abstract
public abstract void stop(); methods
Automatically call Walker’s methods if creature ...
is Walker, Hopper’s for Hopper, etc. public void moveAcross(..) { ... }
}
M. El Dick

Abstract Class (cont’d) Abstract Classes (cont’d)


Object
 Serve as common superclass for more specific ... Component
classes ... Button TextComponent Container

 Needed for polymorphism to work ... JComponent Window

 Closer to the root of the hierarchy ... JTextComponent AbstractButton JPanel ...

 Describe more abstract objects


... JTextArea JTextField ... JMenuItem JButton ...

A fragment of Java library GUI class hierarchy


(abstract classes are boxed)

M. El Dick M. El Dick
Abstract Classes (cont’d) Class Object
 Cannot be instantiated (i.e., cannot create objects)  Every class by default extends library class Object (from java.lang)

 Still, can have constructors


public class Object Methods
 they can be called from constructors of subclasses
{ redefined
(using super)
public String toString() {...} (overridden)
Returns
A class with no abstract methods is called concrete object’s public boolean equals (Object other) {... } as necessary
class name public int hashCode() { ... }
(non-abstract) and
hex address // a few other methods
in memory ...
}

M. El Dick M. El Dick

Calling Superclass’s Constructors Calling Superclass’s Constructors


public class Walker extends Biped  One of the superclass’s constructors is always called
{
 If no explicit call to super,
// Constructor
public Walker(int x, int y, Image leftPic, Image rightPic)  Superclass’s no-args constructor is called by default
{
super(x, y, leftPic, rightPic); Calls
... Biped’s
constructor Must be defined
}
If not defined  syntax error
}

The number / types of parameters


If present, must be passed to super match parameters of
the first statement one of the superclass’s constructors
M. El Dick
Calling Superclass’s Constructors Calling Superclass’s Methods
 Superclass’s constructor calls its superclass’s public class CharlieChaplin Walker
constructor, and so on, extends Walker
all the way up to Object’s constructor {
...
CharlieChaplin
public void nextStep ()
Object
{
super( )
turnFeetIn();
Biped super.nextStep(); Calls Walker’s nextStep
super(...) turnFeetOut();
}
Walker }

M. El Dick M. El Dick

Final Interfaces
 Final method:
 cannot be overridden by subclasses
DanceFloor Aerobics
 Final class: Interface
 cannot be subclassed DanceGroup Waltz

ControlPanel Dance Rumba

Band Cha-Cha-Cha

Dancer Salsa

M. El Dick M. El Dick
Interfaces Interfaces
 Like an abstract class, but no fields or constructors, and A concrete class that implements an interface must
only abstract methods supply all the methods of that interface
public class Waltz implements Dance
public interface Dance
{
{
...
DanceStep getStep (int i);
// Methods:
int getTempo ();
public DanceStep getStep (int i) { ... }
int getBeat (int i);
public int getTempo () { return 750; }
}
public int getBeat (int i) { ... }
...
 “publicabstract” is not written because all the methods }
are public abstract
M. El Dick M. El Dick

public interface SafeToEat public class Pancake


{ implements SafeToEat
Interfaces String getFoodGroup();
int getCaloriesPerServing();
{
...
} }
A class can implement several interfaces

public class Breakfast


 Interface supplies a secondary data type to objects of {
a class that implements that interface private int myTotalCalories = 0; Polymorphism:
... method is called
 You can declare variables and parameters of an public void eat (SafeToEat obj, int servings) based on type
interface type { of SafeToEat,
myTotalCalories += e.g., a Pancake
obj.getCaloriesPerServing () * servings;
Dance d = new Waltz( ); }
}

M. El Dick M. El Dick
Classes Interfaces Classes Interfaces
Similarities Similarities
 Provide secondary data  Provide secondary data  A concrete subclass of an  A concrete class that implements
type to objects of its type to objects of classes abstract class must define all an interface must define all the
subclasses that implement it the inherited abstract methods specified by the
methods interface

 Can extend another class by  Can extend another interface


 Cannot be instantiated if  Cannot be instantiated adding methods and by adding declarations of
abstract overriding some of its abstract methods
superclass’s methods

M. El Dick M. El Dick

Classes Interfaces Classes Interfaces


Differences Differences

 A class can extend only  Has all its methods  All declared methods
 A class can implement
one class defined if concrete, one are abstract
several interfaces
or more abstract
 Can have fields methods if abstract
 Cannot have fields
(except, possibly, public
static final constants)  May belong to a small
 Is part of a hierarchy of hierarchy of
 Have no constructors classes with Object at the interfaces, but this is
 Define its own top not as common
constructors (or get
default constructor)
M. El Dick
Exercise 1
Exercises  Find the errors in the code below
public abstract class A {
public class B extends A {
public double bar() {
System.out.println("B");
public abstract void bar() ; return 0.0;
System.out.println( "B" ); }
} public void bar() {}
}
public class C extends A {
public C(){
super( "C“ );
}
public void display() {
System.out.println( "C" );
M. El Dick }} M. El Dick

public abstract class A { public class B extends A {


public void bar() {
Exercise 2
public asbtract void bar() ; System.out.println("B");
}  Write 2 classes Rectangle and Circle that implement the
} } interface Shape
public class C extends A {  Use class java.awt.Point
public C(){
public interface Shape
super( ); {
} double getPerimeter();
public void bar() { double getArea();
System.out.println( "C" ); }
}}
public static void main(String args[])
{
Shape c = new Circle (new Point (1, 1), 2.5);
System.out.println (c.getArea());
M. El Dick } M. El Dick
import java.awt.Point;
public class Circle implements
Shape
{Exercise 2 public class Rectangle implements
Exercise 3
private Point center;
Shape
private double radius;
{
public Circle (Point c, double r)
private double width, height;
 Write the classes:
{
center = c;
//…  Player (unique number, name, club number)
radius = r;
public double getPerimeter()
 toString()
}
{  International (player with country name)
public double getPerimeter()
return 2 * (width + height);  toString()
{
}
return 2 * Math.PI * r;  Players (a number of unique players)
}
public double getArea()  addPlayer(), isPresent()
public double getArea()
{
{
return width * height;  Use class java.util.Vector to store and manipulate the
return Math.PI * r * r; players
}
}
}
}  Team (maximum 11 players of the same club)
 Test (main)

M. El Dick M. El Dick

Exercise 3 (cont’d) Exercise 4


P.S. Class java.util.Vector  Write a program that simulates a company with employees of
type:
 Growable array of elements (objects of any  Project managers, technicians, developers
type)  The company is identified by a name
 Vector() : create an empty vector  Employees are identified by a serial number
 Also, name, last name, job description
 Void add (object o) : add an element to the vector
 Employees earn different salaries that can be returned via a
 int size () : returns the current number of elements method:
 Object elementAt(int i) : return the element  Project manager: 3000$
 Developer : 1500$
 Technician : 1000$
(to be continued in chapter 6...)  The company can return the salary of an employee given as a
parameter
M. El Dick M. El Dick
(to be continued in chapter 6...)

You might also like