extending classes (contd.) (chapter 15) questionspammann/332/ppt/kak/slides15c.pdfthe official rules...
TRANSCRIPT
Extending Classes (contd.) (Chapter 15)
Questions:
1
1. The following C++ program compiles without any
problems. When run, it even prints out the ‘‘hello’’
called for in line (B) of main. But subsequently
the program aborts with a memory segmentation fault.
Why?
2
class X {
int* p;
int size;
public:
X() { p = 0; size = 0; }
X( int* ptr, int sz ) : size( sz ) {
p = new int[ size ];
for ( int i=0; i<size; i++ ) p[i] = ptr[i];
}
~X() { delete[] p; }
};
class Y : public X {
int n;
public:
Y() {};
Y( int* ptr, int sz, int nn ) : X( ptr, sz ), n( nn ) {}
Y( const Y& other ) : X( other ), n( other.n ) {}
Y& operator=( const Y& other ) {
if ( this == &other ) return *this;
X::operator=( other );
n = other.n;
return *this;
}
};
int main() {
int data[ 3 ] = {3, 2, 1};
Y y1( data, 3, 10 );
Y y2;
y2 = y1; //(A)
cout << "hello" << endl; //(B)
return 0;
}
3
2. In terms of what happens at compile time and what
happens at run time, what’s the difference between
function overloading and function overriding?
4
3. What program declaration makes it possible for a
function to behave polymorphically ?
5
4. What is meant by static binding and what is meant by
dynamic binding?
6
5. Does overload resolution result in static binding or
dynamic binding?
7
6. What is RTTI and what’s it used for?
8
7. What is meant by a polymorphic type?
9
8. While polymorphic behavior of a function is
obviously important, why is the concept of a
polymorphic type important also?
10
Virtual Destructors in C++
Even when a base class does not directly appropriate system resources, you
may still need to declare its destructor virtual if you want polymorphic
destruction of derived-class objects.
11
Consider the case of a vector of pointers to the base-class type, where some
of the pointers are actually pointing to objects of a derived-class type.
Let’s say that you now set up a loop in which you invoke the delete
operator on each of the pointers, with the hope that the destructor invoked
for each object would be the one defined specifically for it.
In other words, you’d want the destructor invocation to behave polymor-
phically. This will only happen if you declare the destructor to be virtual
in the base class.
12
A simple demonstration of a virtual destructor in action, consider .....
#include <iostream>
using namespace std;
class X { // BASE
public:
virtual ~X(); //(A)
};
X::~X(){ cout << "X’s destructor" << endl; } //(B)
class Y : public X { // DERIVED
public:
~Y() { cout << "Y’s destructor" << endl; }
};
class Z : public Y { // DERIVED
public:
~Z() { cout << "Z’s destructor" << endl; }
};
int main() {
X* p = new Z(); //(C)
delete p; //(D)
return 0;
}
13
In main of the above program, we construct an object of type Z and assign
it to a base-class pointer of type X* in line (C). When we invoke delete
on this pointer in line (D), we get the following output from the program:
Z’s destructor
Y’s destructor
X’s destructor
14
What would be the output of the program for the following in main:
Y* q = new Z();
delete q;
What would be the output of the program if the keyword virtual was
dropped in line (A) of the program?
15
Constructor Order Dependencies in C++
Order dependency in a derived-class constructor refers to the order in
which the base-class sub-objects are constructed inside a derived-class ob-
ject; the order in which the specified initializations carried for the data
members of the derived class; etc.
16
class X {
public:
X() { cout << "X object under construction" << endl; }
};
class Y {
public:
Y() { cout << "Y object under construction" << endl; }
};
class Base {
X xobj; // (A)
Y yobj; // (B)
public:
Base() : xobj( X() ), yobj( Y() ) {} // (C)
};
int main() { Base b; }
17
The official rules for the order in which the code for a derived-class con-
structor is executed are:
1. When a derived-class constructor is invoked, first the memory needed
for constructing the derived-class object is appropriated.
2. Next, the constructor of the base-class is invoked to construct the base-
class slice of the derived-class object. (If the derived class has multiple
bases, the base-class constructor for each base is invoked in the order
in which the bases are declared in the header of the derived class, and
regardless of the order used by the programmer in his/her coding of
the derived-class constructor.)
3. If the derived-class constructor uses the member initialization syntax
for the data member of the derived class, invoke the initializers in the
order in which the data members are declared in the class definition,
and regardless of the order they are shown in the member initialization
syntax by the programmer.
4. Execute the code in the body of the derived-class constructor.
18
class X {
public:
virtual void foo(){ cout << "X’s foo invoked" << endl; }
X() { foo(); }
};
class Y : public X {
public:
void foo(){ cout << "Y’s foo invoked" << endl; }
Y() {}
};
int main()
{
Y yobj;
}
19
Abstract Classes in C++
Shape
/\ /\ /\
/ \ / \ / \
---- ---- ----
| | |
| | |
/ | \
/ | \
/ | \
/ | \
/ | \
Circle Rectangle ......
double area( );
double circumference();
class Shape {
public:
virtual double area( );
virtual double circumference();
//....
};
20
class Shape {
public:
virtual double area( ) = 0;
virtual double circumference() = 0;
//....
};
Shape* shapes[ 3 ];
shapes[0] = new Circle( ... );
shapes[1] = new Rectangle( ..... );
shapes[2] = new Rectangle( ..... );
double total_area = 0;
for (int i=0; i < 3; i++ )
total_area += shapes[i]->area(); // (A)
21
#include <iostream>
class Shape {
public:
virtual double area() = 0;
virtual double circumference() = 0;
};
class Circle : public Shape {
protected:
double r;
static double PI;
public:
Circle() { r = 1.0; }
Circle( double r ) { this->r = r; }
double area() { return PI*r*r; }
double circumference() { return 2 * PI * r; }
double getRadius() {return r;}
};
double Circle::PI = 3.14159265358979323846;
class Rectangle : public Shape {
double w, h;
public:
Rectangle() { w=0.0; h = 0.0; }
Rectangle( double w, double h ) { this->w = w; this->h = h; }
double area() { return w * h; }
double circumference() { return 2 * (w + h); }
double getWidth() { return w; }
double getHeight() { return h; }
};
22
int main()
{
Shape* shapes[ 3 ];
shapes[0] = new Circle( 2.0 );
shapes[1] = new Rectangle( 1.0, 3.0 );
shapes[2] = new Rectangle( 4.0, 2.0 );
double total_area = 0;
for (int i=0; i < 3; i++ )
total_area += shapes[i]->area();
cout << "Total area = " << total_area << endl;
}
23
A C++ class is ’abstract’ if it has at least one virtual function that is
pure.
As one would expect, it is not possible to make objects of a class that is
abstract.
Therefore, the sole purpose of an abstract class is to serve as an interface
to the derived classes.
You could also say that an abstract class serves as an organizational prin-
ciple in a class hierarchy.
A pure virtual function that is not defined in a derived class remains a
pure virtual function.
So, in such a case, the derived class is also an abstract class. This allows
us to build an implementation in stages.
24
Shape
/\ /\ /\
/ \ / \ / \
---- ---- ----
| | |
| | |
/ | \
/ | \
/ | \
/ | \
/ | \
Polygon .... CurvedShape
/\ /\ /\ /\ /\ /\
/ \ / \ / \ / \ / \ / \
---- ---- ---- ---- ---- ----
| | | | | |
| | | | | |
/ | \ / | \
/ | \ / | \
/ | \ / | \
/ | \ / | \
Square Rectangle ... Circle Ellipse ......
25
#include <iostream>
class Shape {
public:
virtual double area() = 0;
virtual double circumference() = 0;
};
class Polygon : public Shape {
protected:
int numVertices;
bool starShaped;
};
class CurvedShape : public Shape {
public:
virtual void polygonalApprox() = 0;
};
class Circle : public CurvedShape {
protected:
double r;
static double PI;
public:
Circle() { r = 1.0; }
Circle( double r ) { this->r = r; }
double area() { return PI*r*r; }
double circumference() { return 2 * PI * r; }
double getRadius() {return r;}
void polygonalApprox()
{
26
cout << "polygonal approximation code goes here" << endl;
}
};
double Circle::PI = 3.14159265358979323846;
class Rectangle : public Polygon {
double w, h;
public:
Rectangle() { w=0.0; h = 0.0; numVertices = 0; starShaped = true; }
Rectangle( double w, double h )
{
this->w = w;
this->h = h;
numVertices = 4;
starShaped = true;
}
double area() { return w * h; }
double circumference() { return 2 * (w + h); }
double getWidth() { return w; }
double getHeight() { return h; }
};
int main()
{
Shape* shapes[ 3 ];
shapes[0] = new Circle( 2.0 );
shapes[1] = new Rectangle( 1.0, 3.0 );
shapes[2] = new Rectangle( 4.0, 2.0 );
double total_area = 0;
for (int i=0; i < 3; i++ )
27
total_area += shapes[i]->area();
cout << "Total area = " << total_area << endl;
}
28
Protected and Private Derived Classes in C++
class Derived_class : public Base_class {
//...
};
class Derived_class : private Base_class {
//...
};
results in what’s referred to as implementation inheritance.
This name reflects the fact this kind of derivation is good primarily for
using locally the non-private interface of the base class, but not for making
this inherited interface available to other classes, or even to further derived
classes.
29
A special case of this implementation inheritance is the protected inheri-
tance obtained by a protected derivation, as in
class Derived_class : protected Base_class {
//...
};
Now the non-private interface inherited from the base class is made avail-
able for inheritance to only the subclasses of the Derived class.
30
When you do not carry out a public derivation, you can no longer assign
a Derived* to a Base* without explicit conversion.
For example, in our Employee–Manager example, if we had derived Manager
using the following syntax
class Manager : protected Employee {
// same as before
};
we would no longer be allowed to say
Employee* e3 = new Manager( "ms", "importante" );
because a Manager is no longer automatically an Employee. Now if wish
to make a single list, in the form of a vector, of Employee* types, we must
first use explicit conversion as in
Employee* e3 = (Employee*) new Manager( "ms", "importante" );
31
Employee
^
|
| - - - - - -> ExecutiveRole
|/
Manager
^
|
|
|
Director
class ExecutiveRole {
public:
void sayExecutiveHello(){
cout << "Hello from Executive ranks" << endl;
}
};
32
#include <iostream.h>
#include <mstring.h>
#include <vector.h>
class Employee {
string firstName, lastName;
int age, yearsInService;
//.....
public:
Employee( string fnam, string lnam ) { firstName = fnam; lastName = lnam; }
virtual void print() const { cout << firstName << " " << lastName << endl; }
void sayEmployeeHello() { cout << "hello from Employee class" << endl; }
};
33
class ExecutiveRole {
public:
void sayExecutiveHello(){ cout << "Hello from Executive ranks" << endl; }
};
//class Manager : public Employee, private ExecutiveRole { // WILL NOT COMPILE
class Manager : public Employee, protected ExecutiveRole { // WORKS FINE
short level;
//..
public:
Manager( string fnam, string lnam, short lvl )
: Employee( fnam, lnam ), level( lvl )
{
cout<< "In Manager constructor: ";
sayEmployeeHello();
sayExecutiveHello();
}
void print() const
{
Employee::print();
cout << "level: " << level << endl;
}
};
34
class Director : public Manager {
short grade;
//...
public:
Director( string fnam, string lnam, short lvl, short gd )
: Manager( fnam, lnam, lvl ), grade( gd )
{
cout << "In Director constructor: ";
sayEmployeeHello(); sayExecutiveHello();
}
void print() const
{
Manager::print();
cout << "grade: " << grade << endl << endl;
}
};
int main()
{
vector<Employee*> empList;
Employee* e1 = new Employee( "john", "doe" );
Employee* e2 = (Employee*) new Manager( "jane", "joe", 2 );
Employee* e3 = (Employee*) new Director( "mister", "bigshot", 3, 4 );
empList.push_back( e1 );
empList.push_back( e2 );
empList.push_back( e3 );
vector<Employee*>::iterator p = empList.begin();
while ( p < empList.end() ) (*p++)->print();
35
// e3->sayHi();
Manager* m = new Manager( "jane", "doe", 2 );
m->sayEmployeeHello();
Director* d = new Director( "john", "doe", 3, 4 );
d->sayEmployeeHello();
}
36
Extending Classes in Java
What is accomplished by making a public derivation from a class in C++
is achieved by using the ”extends” clause in Java.
37
class Employee {
private String firstName, lastName;
//...
public Employee( String fnam, String lnam )
{
firstName = fnam;
lastName = lnam;
}
public void print() { System.out.print( firstName + " " + lastName ); }
}
class Manager extends Employee {
private short level;
// ...
public Manager( String fnam, String lnam, short lvl )
{
super( fnam, lnam );
level = lvl;
}
public void print()
{
super.print();
System.out.println( "level: " + level );
}
}
38
Object construction in Java has one feature that is not shared by object
construction in C++:
If a derived-class constructor in Java does not invoke the base class’s con-
structors (or if the base class does not have a no-arg constructor), the
derived-class constructor is allowed to invoke another one of the construc-
tors for the derived class by using the this() construct.
39
class Manager extends Employee {
private short level;
// ...
public Manager( String fnam, String lnam, short lvl ) {
super( fnam, lnam );
level = lvl;
}
public Manager( String fnam, String lnam ) {
this( fnam, lnam, 10 );
}
public void print() {
super.print();
System.out.println( "level: " + level );
}
}
40
With regard to the base-class functions that are available in a derived class,
another very important difference between C++ and Java is as follows:
In C++ a derived-class function of a given name hides all base-class func-
tions of the same name, regardless of their signatures; the hidden names
can only be accessed through the scope operator in the derived class.
That is not the case in Java.
41
//NameLookup.java
class Base {
public void foo() { //(A)
System.out.println( "Base’s foo() invoked" );
}
public void foo( int i ) { //(B)
System.out.println( "Base’s foo( int ) invoked" );
}
public void foo( int i, int j ) { //(C)
System.out.println( "Base’s foo( int, int ) invoked" );
}
}
class Derived extends Base {
public void foo() { //(D)
System.out.println( "Derived’s foo() invoked" );
}
}
public class Test {
public static void main( String[] args )
{
Derived d = new Derived();
d.foo(); // Derived’s foo() invoked //(E)
d.foo( 3 ); // Base’s foo( int ) invoked //(F)
d.foo( 3, 4 ); // Base’s foo( int, int ) invoked //(G)
}
}
42
//NameLookup.cc // WILL NOT COMPILE
#include <iostream>
using namespace std;
class Base {
public:
void foo() { //(A)
cout << "Base’s foo() invoked" << endl;
}
void foo( int i ) { //(B)
cout << "Base’s foo( int ) invoked" << endl;
}
void foo( int i, int j ) { //(C)
cout << "Base’s foo( int, int ) invoked" << endl;
}
};
class Derived : public Base {
public:
void foo() { cout << "Derived’s foo() invoked" << endl; } //(D)
};
int main()
{
Derived d;
d.foo(); //(E)
d.foo( 3 ); //(F)
d.foo( 3, 4 ); //(G)
}
43
Restrictions on Overriding Functions in Java
The definition of an overriding method in a derived class must not violate
the following restrictions:
1. The return type of an overriding method in a derived class must be the
same as the return type of the overridden method in the base class.
class X {
public float foo( double m ) { return m; }
}
class Y extends public X {
public double foo( double n ) { return n; } // Error
}
44
2. The access restriction for an overriding method can be no tighter than
the restriction on the base-class overridden method. So if the access
restriction on the base-class method is, say, protected, the overriding
method in the derived class can either be protected or public, but
not private.
45
3. The exception specification for an overriding function in a derived class
must be a subset of the exception specification on the overridden base-
class method.
class Exception_1 extends Exception {}
class Exception_2 extends Exception {}
class X {
private int m;
public X( int mm ) { m = mm; }
public void foo() throws Exception_1 {
System.out.println( "X’s foo invoked" );
throw new Exception_1();
}
}
class Y extends X {
private int n;
public Y( int mm, int nn ) { super( mm ); n = nn; }
public void foo() throws Exception_2 { // WRONG
System.out.println( "Y’s foo invoked" );
throw new Exception_2();
}
}
46
class Exception_1 extends Exception {}
class Exception_2 extends Exception {}
class X {
private int m;
public X( int mm ) { m = mm; }
public void foo() throws Exception_1 {
System.out.println( "X’s foo invoked" );
throw new Exception_1();
}
}
class Y extends X {
private int n;
public Y( int mm, int nn ) { super( mm ); n = nn; }
public void foo() {
System.out.println( "Y’s foo invoked" );
}
}
47
Constructor Order Dependencies in Java
1. Invoke the constructor of the derived class by appropriating the re-
quired amount of memory and set all the data members in this mem-
ory to their default values (zero for all numeric types, false for boolean,
\u0000 for char, and null for object reference).
2. Invoke the base-class constructor.
3. If there is any initialization code attached to any of the data members
in the base class, it is executed and the data members initialized.
4. Execute the code in the body of the base class constructor. This base
class constructor could be a no-arg constructor.
5. If there is any initialization code attached to any of the data mem-
bers in the derived class, it is now executed and the data members
initialized.
6. Execute the code in the body of the derived class constructor.
48
class X {
void foo(){ System.out.println( "X’s foo invoked" ); }
public X() { foo(); }
}
class Y extends X {
void foo(){ System.out.println( "Y’s foo invoked" ); }
public Y() {}
}
class Test {
public static void main( String[] args )
{
Y yobj = new Y();
}
}
The output of this program is
Y’s foo invoked
49
Abstract Classes in Java
abstract class Shape {
abstract public double area( );
abstract public double draw();
//....
}
50
abstract class Shape {
abstract protected double area();
abstract protected double circumference();
}
abstract class Polygon extends Shape {
protected int numVertices;
protected boolean starShaped;
}
abstract class curvedShape extends Shape {
abstract public void polygonalApprox();
}
class Circle extends curvedShape {
protected double r;
protected static double PI = 3.14159265358979323846;
public Circle() { r = 1.0; }
public Circle( double r ) { this.r = r; }
public double area() { return PI*r*r; }
public double circumference() { return 2 * PI * r; }
public double getRadius() {return r;}
public void polygonalApprox()
{
System.out.println("polygonal approximation code goes here");
}
}
51
class Rectangle extends Polygon {
double w, h;
public Rectangle() { w=0.0; h = 0.0; numVertices = 0; starShaped = true; }
public Rectangle( double w, double h )
{
this.w = w;
this.h = h;
numVertices = 4;
starShaped = true;
}
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }
public double getWidth() { return w; }
public double getHeight() { return h; }
}
class test {
public static void main( String[] args )
{
Shape[] shapes = new Shape[ 3 ];
shapes[0] = new Circle( 2.0 );
shapes[1] = new Rectangle( 1.0, 3.0 );
shapes[2] = new Rectangle( 4.0, 2.0 );
double total_area = 0;
for (int i=0; i < shapes.length; i++ )
total_area += shapes[i].area();
System.out.println("Total area = " + total_area);
}
}
52
public abstract class WindowAdapter implements WindowListener
public void windowActivated( WindowEvent e ) {};
public void windowClosed( WindowEvent e ) {};
public void windowClosing( WindowEvent e ) {};
public void windowDeactivated( WindowEvent e ) {};
public void windowDeiconified( WindowEvent e ) {};
public void windowIconified( WindowEvent e ) {};
public void windowOpened( WindowEvent e ) {}; }
53
With regard to abstract methods, Java has one feature not possessed by
C++:
In a class hierarchy, any method inherited from any of the superclasses can
be declared to be abstract, making that particular class in the hierarchy
an abstract class.
This can be useful when it is necessary to block the inherited definition of
a method to one or more derived classes in a class hierarchy.
54
Interfaces in Java
interface Drawable {
public void setColor( Color c );
public void setPosition( double x, double y );
public void draw( DrawWindow dw );
}
class DrawableRectangle extends Rectangle implements Drawable {
private Color c;
private double x, y;
public DrawableRectangle( double w, double h ) { super( w, h ); }
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y = y; }
public void draw( DrawWindow dw ) { dw.drawRect( x, y, w, h, c ); }
}
55
____________
| Shape |
| (abstract) |
------------
/\ /\
/ \ / \
---- ----
| | - - - - -
| | | Drawable |
| | - - - - -
----------- --------- /\ /\
| Rectangle | | Circle | / \ / \
----------- --------- ---- ----
/\ /\ | |
/ \ / \
---- ---- | |
| \
| \ / |
| \
| \ / |
| \
| \ / |
| \
| \ / |
| \
| \/ |
| \
| / \ |
| \
| / \ |
---------------------------- -------------------------
| DrawableRectangle | | DrawableCircle |
---------------------------- -------------------------
56
Shape[] shapes = new Shape[3];
Drawable[] drawables = new Drawable[3];
DrawableCircle dc = new DrawableCircle( 1.1 );
DrawableSquare ds = new DrawableSquare( 2.5 );
DrawableRectangle dr = new DrawableRectangle( 2.3, 4.5 );
shapes[0] = dc;
shapes[1] = ds;
shapes[2] = dr;
drawables[0] = dc;
drawables[1] = ds;
drawables[2] = dr;
57
double total_area = 0;
for (int i = 0; i < shapes.length; i++ ) {
total_area += shapes[i].area();
drawables[i].setPosition( i*10.0, i*10.0 ); //
drawables[i].draw( draw_window ); //
}
58
abstract class Shape {
abstract protected double area();
abstract protected double circumference();
}
class Circle extends Shape {
protected double r;
protected static double PI = 3.14159265358979323846;
public Circle( double r ) { this.r = r; }
public double area() { return PI*r*r; }
public double circumference() { return 2 * PI * r; }
}
class Rectangle extends Shape {
double w, h;
public Rectangle( double w, double h )
{
this.w = w;
this.h = h;
}
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }
}
interface Drawable {
public void setColor( Color c );
public void setPosition( double x, double y );
public void draw( DrawWindow dw );
}
59
class DrawableRectangle extends Rectangle implements Drawable {
private Color c;
private double x, y;
public DrawableRectangle( double w, double h ) { super( w, h ); }
// Implementations of the methods inherited from the interface:
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y = y; }
public void draw( DrawWindow dw ) { dw.drawRect( x, y, w, h, c ); }
}
class DrawableCircle extends Circle implements Drawable {
private Color c;
private double x, y;
public DrawableCircle( double rad ) { super( rad ); }
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y = y; }
public void draw( DrawWindow dw ) { dw.drawCircle( x, y, r, c ); }
}
class Color {
int R, G, B;
}
60
class DrawWindow {
public DrawWindow() {};
public void drawRect( double x, double y, double width, double height, Color
{
System.out.println( "Code for drawing a rect needs to be invoked" );
}
public void drawCircle( double x, double y, double radius, Color col )
{
System.out.println( "Code for drawing a circle needs to be invoked" );
}
}
class test {
public static void main( String[] args )
{
Shape[] shapes = new Shape[3];
Drawable[] drawables = new Drawable[3];
DrawableCircle dc = new DrawableCircle( 1.1 );
DrawableRectangle dr1 = new DrawableRectangle( 2.5, 3.5 );
DrawableRectangle dr2 = new DrawableRectangle( 2.3, 4.5 );
shapes[0] = dc;
shapes[1] = dr1;
shapes[2] = dr2;
drawables[0] = dc;
drawables[1] = dr1;
drawables[2] = dr2;
int total_area = 0;
DrawWindow dw = new DrawWindow();
61
for (int i = 0; i < shapes.length; i++ ) {
total_area += shapes[i].area();
drawables[i].setPosition( i*10.0, i*10.0 ); // (A)
drawables[i].draw( dw ); // (B)
}
System.out.println("Total area = " + total_area);
}
}
62
Code for drawing a circle needs to be invoked
Code for drawing a rect needs to be invoked
Code for drawing a rect needs to be invoked
Total area = 21
63
Implementing Multiple Interfaces in Java
interface Scalable {
public Shape scaleTransform();
}
class DrawableScalableRectangle
extends Rectangle
implements Drawable, Scalable {
// the methods of the Drawable and Scalable interfaces
// must be implemented here
}
64
Extending Interfaces in Java
interface Drawable {
public void setColor( Color c );
public void setPosition( double x, double y );
public void draw( DrawWindow dw );
}
interface DrawScalable extends Drawable {
public void drawScaledShape( int scaleFactor, DrawWindow dw );
}
65
class DrawScalableRectangle extends Rectangle implements DrawScalable
private Color c;
private double x, y;
public DrawScalableRectangle( double w, double h ) { super( w,
// Implementations of the methods inherited from the interface:
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y
public void draw( DrawWindow dw ) { dw.drawRect( x, y, w, h, c
public void drawScaledShape( int scaleFactor, DrawWindow dw )
{
dw.drawScaledRect( x, y, w, h, c, scaleFactor );
}
}
66
abstract class Shape {
abstract protected double area();
abstract protected double circumference();
}
class Circle extends Shape {
protected double r;
protected static double PI = 3.14159265358979323846;
public Circle( double r ) { this.r = r; }
public double area() { return PI*r*r; }
public double circumference() { return 2 * PI * r; }
}
class Rectangle extends Shape {
double w, h;
public Rectangle( double w, double h )
{
this.w = w;
this.h = h;
}
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }
}
interface Drawable {
public void setColor( Color c );
public void setPosition( double x, double y );
public void draw( DrawWindow dw );
}
67
interface DrawScalable extends Drawable {
public void drawScaledShape( int scaleFactor, DrawWindow dw );
}
class DrawScalableRectangle extends Rectangle implements DrawScalable {
private Color c;
private double x, y;
public DrawScalableRectangle( double w, double h ) { super( w, h ); }
// Implementations of the methods inherited from the interface:
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y = y; }
public void draw( DrawWindow dw ) { dw.drawRect( x, y, w, h, c ); }
public void drawScaledShape( int scaleFactor, DrawWindow dw )
{
dw.drawScaledRect( x, y, w, h, c, scaleFactor );
}
}
class DrawScalableCircle extends Circle implements DrawScalable {
private Color c;
private double x, y;
public DrawScalableCircle( double rad ) { super( rad ); }
public void setColor( Color c ) { this.c = c; }
public void setPosition( double x, double y ) { this.x = x; this.y = y; }
public void draw( DrawWindow dw ) { dw.drawCircle( x, y, r, c ); }
public void drawScaledShape( int scaleFactor, DrawWindow dw )
{
dw.drawScaledCircle( x, y, r, c, scaleFactor );
}
68
}
class Color {
int R, G, B;
}
class DrawWindow {
public DrawWindow() {};
public void drawRect( double x, double y, double width, double height, Color
{
System.out.println( "Code for drawing a rect needs to be invoked" );
}
public void drawScaledRect( double x, double y, double width,
double height, Color col, int scale )
{
System.out.println( "Code for drawing a scaled rect needs to be invoked"
}
public void drawCircle( double x, double y, double radius, Color col )
{
System.out.println( "Code for drawing a circle needs to be invoked" );
}
public void drawScaledCircle( double x, double y, double radius,
Color col, int scale )
{
System.out.println( "Code for drawing a scaled circle needs to be invoked"
}
}
69
class test {
public static void main( String[] args )
{
Shape[] shapes = new Shape[3];
DrawScalable[] drawScalables = new DrawScalable[3];
DrawScalableCircle dc = new DrawScalableCircle( 1.1 );
DrawScalableRectangle dr1 = new DrawScalableRectangle( 2.5, 3.5 );
DrawScalableRectangle dr2 = new DrawScalableRectangle( 2.3, 4.5 );
shapes[0] = dc;
shapes[1] = dr1;
shapes[2] = dr2;
drawScalables[0] = dc;
drawScalables[1] = dr1;
drawScalables[2] = dr2;
int total_area = 0;
DrawWindow dw = new DrawWindow();
for (int i = 0; i < shapes.length; i++ ) {
total_area += shapes[i].area();
drawScalables[i].setPosition( i*10.0, i*10.0 ); // (A)
drawScalables[i].drawScaledShape( 2, dw ); //
}
System.out.println("Total area = " + total_area);
}
}
70
Code for drawing a scaled circle needs to be invoked
Code for drawing a scaled rect needs to be invoked
Code for drawing a scaled rect needs to be invoked
Total area = 21
71
Constants in Interfaces
class A { public static final double PI = 3.14159; }
class test {
//....
void foo()
{
double x = A.PI;
//....
}
}
72
interface A { public static final double PI = 3.14159; }
class test implements A {
//....
void foo()
{
double x = PI;
//....
}
}
73