JavaClass - Lecture6 - Abstract Classes & Int
JavaClass - Lecture6 - Abstract Classes & Int
Lecture 6
Abstraction
3/28/2007 Lecture 6
Example abstract class
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference();
// semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
3/28/2007 Lecture 6
Example abstract class (cont’d)
3/28/2007 Lecture 6
Abstract Class: Example
• An abstract class often contains abstract
methods, though it doesn’t have to
– Abstract methods consist of only methods
declarations, without any method body
public abstract class Vehicle
{
String name;
Lecture 7
Single vs. Multiple Inheritance
• Some object-oriented languages allow
multiple inheritance, which allows a class to
be derived from two or more classes,
inheriting the members of all parents
• The price: collisions, such as the same
variable name, same method name in two
parents, have to be resolved
• Java decision: single inheritance, meaning
that a derived class can have only one parent
class
3/28/2007 Lecture 6
Java Interface
• A Java interface is a collection of
constants and abstract methods
– abstract method: a method header without a
method body; we declare an abstract
method using the modifier abstract
– since all methods in an interface are
abstract, the abstract modifier is usually
left off
A semicolon immediately
follows each method header
No method in an
3/28/2007 Lecture 6 interface has a definition (body)
Implementing an Interface
• A class formally implements an interface by
– stating so in the class header in the
implements clause
– a class can implement multiple interfaces:
the interfaces are listed in the implements
clause, separated by commas
3/28/2007 Lecture 6
Implementing Interfaces
public class Something implements Doable
{
public void doThis ()
{ implements is a
// whatever reserved word
}
// etc.
}
3/28/2007 Lecture 6
Interfaces: Examples from
Java Standard Class Library
if (obj1.compareTo(obj2) < 0)
System.out.println(“obj1 is less than
obj2”);
3/28/2007 Lecture 6
Polymorphism via Interfaces
• Define a polymorphism reference through
interface
– declare a reference variable of an interface type
Doable obj;
• An interface provides
• A superclass
provides a secondary a secondary data type
to objects of classes
data type to objects
that implement that
of its subclasses.
interface.
• An abstract class
cannot be • An interface cannot
be instantiated.
instantiated.
3/28/2007 Lecture 6
Classes Interfaces
Similarities