You are on page 1of 2

Lesson 4: Composition, Abstract Classes and Interface

I. Terminologies
a. Composition –
o or aggregation;
o one or more members of a class are objects of one or more classes;
o “has-a” relationship.
b. Abstract Classes – a class that is declared with the reserved word abstract in its
heading.
c. Interface –
o a type of class that contains only abstract methods and/or named constants;
o defined using the reserved word interface in place of the reserved word
class

II. Rules in Abstract Class


a. An abstract class can contain instance variables, constructors, the finalizer, and
nonabstract methods.
b. An abstract class can contain an abstract method(s).
c. If a class contains an abstract method, then the class must be declared abstract.
d. You cannot instantiate an object of an abstract class. You can only declare a reference
variable of an abstract class type.
e. You can instantiate an object of a subclass of an abstract class, but only if the subclass
gives the definition of all the abstract methods of the superclass.

III. Sample Program

public abstract class Shape {


{ return radius;
public abstract double area(); }
public abstract double perimeter(); public double area()
} {
return Math.PI*Math.pow(radius,
--------------------------------------- 2);
}
public class Circle extends Shape public double perimeter()
{ {
private double radius; return 0;
}
public Circle() }
{
radius=0.0; -------------------------------------
}
public Circle(double r) public class Rectangle extends Shape
{ {
radius=r; public double length, width;
}
public Rectangle(double length,
public double getRadius() double width)
{
New Era University
Computer Programming 2 Page 1
Lesson 4: Composition, Abstract Classes and Interface
this.length=length;
this.width=width;
}

public double getLength()


{
return length;
}
public double getWidth()
{
return width;
}
public double area()
{
return length*width;
}
public double perimeter()
{
return (2*length)+(2*width);
}
}

---------------------------------------

public class Square extends Rectangle


{
public Square(double l, double w)
{
super(l,w);
}

public double area()


{
return length*length;
}
public double perimeter()
{
return 4*length;
}
}

New Era University


Computer Programming 2 Page 2

You might also like