computer science a 9: 3/11. inheritance today: inheritance (jc 11.1-11.3 – ccj 9.1-9.3) i have to...

26
Computer Science A 9: 3/11

Upload: gavin-wilcox

Post on 17-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Computer Science A 9: 3/11

InheritanceToday:

• Inheritance (JC 11.1-11.3 – CCJ 9.1-9.3)

• I have to leave at 11am (but you can stay)

DataSet for BankAccountspublic class DataSet{

// Modified for BankAccount objects

. . .

public void add(BankAccount x) {

sum = sum + x.getBalance();

if(count==0||maximum.getBalance()<x.getBalance())

maximum = x;

count++;

}

public BankAccount getMaximum(){ return maximum; } private double sum;

private BankAccount maximum;

private int count;

}

DataSet for Coinspublic class DataSet{ // Modified for Coin objects . . . public void Coin x) { sum = sum + x.getValue(); if(count==0||maximum.getValue()<x.getValue()) maximum = x; count++; } public Coin getMaximum(){ return maximum; } private double sum; private Coin maximum; private int count; }

Interfacepublic interface Measurable {

double getMeasure();

}

Measurable is an interface – a description of what a class my contains

InterfaceSome classes my ”implement” this interface. This means that they

contain all the methods described in the interface.

public class BankAccount implements Measurable { public double getMeasure() { return balance; }

// Additional methods and fields

}

public class Coin implements Measurable {

public double getMeasure() { return value; }

. . .

}

General datasetpublic class DataSet { public void add(Measurable x) { sum = sum + x.getMeasure(); if(count==0||maximum.getMeasure()<x.getMeasure()) maximum = x; count++; } public Measurable getMaximum() { return maximum; }

private double sum; private Measurable maximum; private int count; }

Converting objects• You can convert from a class type to an interface type,

provided the class implements the interface • BankAccount account = new BankAccount(10000);Measurable x = account; // OK

• Coin dime = new Coin(0.1, "dime");Measurable x = dime; // Also OK

• Cannot convert between unrelated typesMeasurable x = new Rectangle(5,10,20,30);

// ERRORBecause Rectangle doesn't implement Measurable

casts• Add coin objects to DataSet

DataSet coinData = new DataSet();coinData.add(new Coin(0.25, "quarter"));coinData.add(new Coin(0.1, "dime"));. . .Measurable max = coinData.getMaximum(); // Get the largest coin

• What can you do with it? It's not of type CoinString name = max.getName(); // ERROR

• You need a cast to convert from an interface type to a class type

• You know it's a coin, but the compiler doesn't. Apply a cast:Coin maxCoin = (Coin) max;String name = maxCoin.getName();

• If you are wrong and max isn't a coin, the compiler throws an exception

Polymorphism• Interface variable holds reference to object of a class

that implements the interfaceMeasurable x;x = new BankAccount(10000);x = new Coin(0.1, "dime"); Note that the object to which x refers doesn't have type Measurable; the type of the object is some class that implements the Measurable interface

• You can call any of the interface methods:double m = x.getMeasure();

• Which method is called?

Polymorphism • Depends on the actual object.  • If x refers to a bank account, calls BankAccount.getMeasure

• If x refers to a coin, calls Coin.getMeasure • Polymorphism (many shapes): Behavior can

vary depending on the actual type of an object • Called late binding: resolved at runtime • Different from overloading; overloading is

resolved by the compiler (early binding)

interface MyShapeinterface MyShape{

void drawOn(JCanvas canvas);

}

class Treeclass Tree implements MyShape{ Tree(int x,int y){this.x=x; this.y=y;} int x,y; public void drawOn(JCanvas canvas){ canvas.drawArc(x,y,200,200,290,320); canvas.drawLine(x+80,y+300,x+80,y+180); canvas.drawLine(x+120,y+300,x+120,y+180); }}

class Carclass Car implements MyShape{ Car(int x,int y){this.x=x; this.y=y;} int x,y; public void drawOn(JCanvas canvas){ canvas.drawRect(x,y+50,300,50); canvas.drawLine(x+50,y+50,x+100,y); canvas.drawLine(x+100,y,x+200,y); canvas.drawLine(x+200,y,x+250,y+50); canvas.drawOval(x+50,y+100,50,50); canvas.drawOval(x+200,y+100,50,50); }}

class MyShapeTestport javax.swing.*;public class MyShapeTest{ public static void main(String args[]){ JFrame frame=new JFrame("MyShapes"); frame.setSize(600,600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JCanvas canvas=new JCanvas(); frame.add(canvas); MyShape s1=new Car(10,300); MyShape s2=new Car(270,400); MyShape s3=new Tree(330,40); s1.drawOn(canvas); s2.drawOn(canvas); s3.drawOn(canvas); frame.setVisible(true); }}

Example

And more…An interface is a placeholder for a number of

classes.

Inheritance is also that you can extend a class. This is the corner-stone of object-oriented programming and code reuse:

Extend classes

Override methods

Protect access

Exampleclass Point{

int x; int y;

Point(int x,int y){

this.x=x; this.y=y;

}

public String toString(){

return "("+x+","+y+")";

}

}

Exampleclass Point3D extends Point{

int z;

Point3D(int x,int y,int z){

super(x,y);

this.z=z;

}

public String toString(){

return "("+x+","+y+","+z+")";}

}

ExamplePoint a=new Point(2,4);

System.out.println(a.toString());

Point3D b=new Point3D(7,9,13);

System.out.println(b.toString());

A Point3D ”is-a” Point object and may be used as a Point object

Basics:class A{

int f(){return 2;}

}

class B extends A{

int f(){return 3;}

}

..

A a1=new A(); int i1=a1.f(); // ok, i=2

A a2=new B(); int i1=a2.f(); // ok, i=3

B b1=new A(); // not ok

B b2=new B(); int i1=b2.f(); // ok, i=3

Inheriting Methods • Override method: • Supply a different implementation of a method that exists

in the superclass • Must have same signature (same name and same

parameter types) • If method is applied to an object of the subclass type, the

overriding method is executed• Inherit method: • Don't supply a new implementation of a method that

exists in superclass • Superclass method can be applied to the subclass

objects• Add method: • Supply a new method that doesn't exist in the superclass • New method can be applied only to subclass objects

Inheriting Instance Fields • Can't override fields

• Inherit field: All fields from the superclass are automatically inherited

• Add field: Supply a new field that doesn't exist in the superclass

Constructorspublic class CheckingAccount extends BankAccount {

public CheckingAccount(double initialBalance) {

// Construct superclass

super(initialBalance);

// Initialize transaction count

transactionCount = 0;

} . . . }

super followed by a parenthesis indicates a call to the superclass constructor

Must be the first statement in subclass constructor

If subclass constructor doesn't call superclass constructor, default superclass constructor is used (no arguments)

Cast an instanceofclass A{ .. } class B extends A{ ..void g().. }

A a= new B(); // oka.g(); // not okIf(a instanceof B){ B b= (B) a; // cast b.g(); // ok}

Access controlJava has four levels of controlling access to fields, methods,

and classes: • public access

– Can be accessed by methods of all classes• private access

– Can be accessed only by the methods of their own class

• protected access – Access from subclasses

• package access – The default, when no access modifier is given – Can be accessed by all classes in the same package – Good default for classes, but extremely unfortunate for

field