Inheritance & Polymorphism

advertisement

Object Oriented Concepts in

Java

Objects

Inheritance

Encapsulation

Polymorphism

= slide covered in class – others for reference

Sample class…

public class Bicycle

{ public int cadence; public int gear; public int speed;

} gear = startGear; cadence = startCadence; speed = startSpeed;

} public void setCadence(int newValue) { cadence = newValue; public void setGear(int newValue) { gear = newValue;

} public void applyBrake(int decrement) { speed -= decrement;

} public void speedUp(int increment) { speed += increment;

}

What is the class name?

What are the attributes? (fields)?

What does the class “do”?

Methods?

Pick out all the java language words e.g. public is a reserved java word..

Notice..

indentation

Brackets { }

Java words

Case conventions ..

Comments

} public class Bicycle { public int cadence; public int gear; public int speed;

Comments in your code

}

// the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed, int startGear) {

// ALWAYS comment your code gear = startGear; cadence = startCadence; // each method speed = startSpeed;

// each attribute..

// the Bicycle class has four methods public void setCadence(int newValue) { cadence = newValue;

} public void setGear(int newValue) { gear = newValue;

} public void applyBrake(int decrement) { speed -= decrement;

} public void speedUp(int increment) { speed += increment;

}

Class vs Instance Objects

• Class members

– class fields

– class methods

• Instance members

– instance fields

– instance methods

Class Members

• Class members (fields and methods) are associated with the class in which they are defined

– exist only once, a single copy

– declared using the static keyword

– class members are accessed using the class name

ClassName.classMemberName

Class fields and Methods

• Class fields

– a class field has the same value for all instances of the object

– a class field declared with a final modifier is a constant static final double PI=3.14159;

Why would you do this?

• Class methods

– a class method cannot use any instance members

(fields or methods)

– Used for a method that is same for all objects

Class method

class MyUtils { public static double mean(int[] p) { int sum = 0; // sum of all the elements for (int i=0; i<p.length; i++) { sum += p[i];

} return ((double)sum) / p.length;

}//endmethod mean

}

// Called from outside the MyUtils class – uses Class name double avgAtt = MyUtils .mean(attendance);

Instance members

• Instance members are associated with instances of the class

– exist for each separate instance

– copied as the object is instantiated

– instance fields in different instance objects can have different values

Example – class vs instance

public class BankAccount{

// instance fields

String name; double balance;

// class field static double interestRate;

// instance method public double getBalance(){ return balance;

}

// class method public static double getRate(){ return interestRate;

}

...

}

Example – class vs instance

• Code to setup and use BankAccounts

//instantiate a BankAccount default constructor

BankAccount myAcc = new BankAccount(...);

// access its instance field balance

System.out.println(myAcc.getBalance());

// access its class field interestRate

System.out.println(BankAccount.interestRate);

Class name

Method Overloading

• Defining methods within the same class with the same name but with different parameter lists

• Java compiler determines which method to call based on the parameter list

• Often used for constructors

BankAccount(String name){ this.name=name; this.balance=0;

}

BankAccount(String name, double balance){ this.name=name; this.balance=balance;

};

Inheritance

• Inheritance allows classes to be considered in a hierarchy with the data and methods of the parent (super) class being passed onto

(inherited) by the child (sub) classes and not needed in their specifications

• implemented using the extends keyword

• e.g. class subClass extends superClass {

}

• an instance of subClass can also be treated as an instance of the superClass

• Examples?

Object class

• Every class defined has a superclass

• If a superclass is not explicitly defined it is the superclass java.lang.Object

• Object is a special class

– the only class that does not have a superclass

– all Java classes inherit the methods of Object

– instances of any class can be treated as an instance of Object

– all arrays are also considered instances of Object

Inheritance example

public class LoanAccount extends BankAccount{ double loanAmount; int loanPeriod; // no of yrs

...

}

• Bank account had name and balance

• LoanAccount has extra fields specific to Loan accounts

Super

• Constructors are not inherited by subclasses

• A subclass should call the constructor of its superclass to perform the initialisation on the instance fields that the superclass is responsible for

• This is done using the super reference

• super(param1, param2,…) must always be the first line in the subclass constructor code

super Example

public class BankAccount{

String name; double balance=0; public BankAccount (String name){ this.name=name;

}

...

} public class LoanAccount extends BankAccount{ double loanAmount; int loanPeriod; // no of yrs public LoanAccount(name, amt, period){ super(name); this.loanAmount=amt; this.loanPeriod=period;

}

Points about Inheritance

• Multiple Inheritance

– a Java class may only extend from one superclass

- multiple inheritance is not supported

(see interfaces for work around)

• A class that is declared with the final modifier cannot be extended or subclassed

This allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior. E.g. Java.lang. String class

Points about Inheritance

public final class MyFinalClass

{ ..

} public class NotAllowed extends

MyFinalClass {...} // forbidden

Points about Inheritance

• Working within a hierarchy

– any object of a subclass can be assigned to an object of a superclass

– any object of a superclass can be assigned to an object of a subclass with an appropriate cast

BankAccount myAcc = new BankAccount(…); //superclass

LoanAccount myLoan = new LoanAccount(…); //subclass myAcc = myLoan; // OK assign subclass to superclass myLoan = myAcc // not OK why not?

myLoan = (LoanAccount) myAcc; // OK if(myAcc instanceOf LoanAccount)

LoanAccount myLoan = (LoanAccount) myAcc; // better

Overriding Methods

• Overriding is where a subclass decides to supply its own version of an instance method already supplied by its superclass

– general or default method provided in superclass

– more specialised method provided in subclass

– Any examples?

class Animal{

} public void move(){

System.out.println("Animals can move");

}

The benefit of overriding is: ability to define a behavior that's class Dog extends Animal{ specific to the sub class type. public void move(){

System.out.println("Dogs can walk and run");

}

}

In OO terms, overriding means public class TestDog{ to override the public static void main(String args[]){ functionality of any

Animal a = new Animal(); // Animal reference and object existing method.

Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class. This method overrides the animal Move method

}

}

toString()

• Example - toString() method -

• The root Object class has a toString() method which allows an object of the class to be output as a string public String toString();

• The toString() method is overridden at all levels in the hierarchy so that you can write out details of an object in whatever suits your object

• Useful for outputing details of any object

• System.out.println(“Account details: “+myAcc); string concatenation automatically invokes a toString() on myAcc to convert it to a String

Overriding example

public class BankAccount { public String toString(){

String s=“Bank Account for ”; s+=name+”\nbalance= “+balance; return s;

What happens if you

} don’t override the

} toString() method?

public class LoanAccount extends BankAccount{

} public String toString(){

String s=“\nLoan Account for ”; s+=name+”\nbalance= “+balance; s+=“Loan of ”+loanAmt; s+=“ for ”+loanPeriod+ “years”; return s;

}

super

• use the super keyword to invoke the superclass version of an overridden method

// Bank Account toString method public String toString(){

String s=“Account for ”; s+=name+”\nbalance= “+balance; return s;

}

// Loan Account toString method public String toString(){

String s= super.toString(); s+=“Loan of ”+loanAmt; s+=“ for ”+loanPeriod+ “years”; return s;

}

Overriding

• Where there are several instances of the same method in a hierarchy – the one in the closest subclass is always used.

• Even if an object of the subclass is assigned to an object of the superclass and method is invoked from the subclass.

System.out.println(myAcc); uses BankAccount toString()

System.out.println(myLoan); uses LoanAccount toString() myAcc=myLoan;

System.out.println(myAcc); still uses LoanAccount toString()

Dynamic Binding

• Overriding uses dynamic binding or dynamic method lookup to find the correct method at run time.

• Dynamic binding is also known as virtual method invocation

• Note: Overriding is not the same as Overloading

Overloading does not use dynamic binding (because overloading is understood at compile time.)

Dynamic Binding

• Animal myAnimal = new Dog();

The variable on the left is type Animal, but the object on the right is type Dog. If the Dog class has a method that is the same as a method in the Animal class, then the version of the method in the Dog class will be called. For instance, if both classes define a method called show(), and you do this: myAnimal.show(); the version of show() in the Dog class will be called. The type of the object that is assigned to the Animal variable determines the method that is called.

When the compiler scans the program and sees that statement it knows that myAnimal is of type Animal, but the compiler also knows that myAnimal can be a reference to any class derived from Animal. Therefore, the compiler doesn't know what version of show() that statement is calling. It's not until the assignment:

Animal myAnimal = new Dog(); is executed at runtime that the version of show() is determined: = dynamic binding

Polymorphism

• Overriding + dynamic binding = polymorphism

• Polymorphism “literally: different forms”..

– is the ability of different objects to respond to the same message (method) in their own way

• Need examples to understand this…

Polymorphism example

abstract class Account

{ int balance; abstract void withdraw( int amount);

}

An account class,

With two subclasses – fixed account, loan account – both of which withdraw money in their own way class LoanAccount extends Account

{ void withdraw( int amount)

{ /* Some sort of calculation specific to withdrawaing from a loan account.. */ }

} class FixedAccount extends Account

{ void withdraw( int amount)

{ /* a calcalculation specific to withdrawing from a fixed accounts

*/

}

}

Polymorphism example

//In some other piece of code.. An object called “MyAcct”.. wants to

Withdraw 40 euro...//

MyAcct.withdraw(40);

How it withdraws money will be decided at run time when the system examines its object type..fixedAccount versus

LoanAcct..This is polymorphism.

Why is this important?

What coding efficiency do you gain from this?

Supposing the behaviour of withdrawing money from a locan account changed..Or you added a new type of account..

Encapsulation

• Encapsulation is the packaging of the object’s fields

(and internal methods) within a protective shell/capsule of its methods

– an object has a “public” interface that other objects use to communicate with it

– an object maintains “private” information that can be changed without affecting other objects that depend on it or use it

– “blackbox” effect

• Encapsulation achieved using Information Hiding.

• Think “coffee machine”…

Encapsulation

• To implement encapsulation

– All fields should be private

– Include ‘get’ and ‘set’ methods (accessor methods) for all fields that need to be accessed by users

– Hide internal methods (i.e. methods that are not relevant to users but are only used by the class itself).

Information Hiding

• Information Hiding – reveal only what is needed to the user of the object

– hides implementation details from user

– facilitates maintenance

– protects against willful or accidental damage

– keeps API simple and “uncluttered”

– facilitates ease of understanding and use

Accessibility Modifiers

• Information Hiding implemented through accessibility modifiers

– public = accessible to any other object

– private = accessible within the object itself

– protected = accessible within the object and any of its subclasses

(and to all classes within the package)

Java Packages

& Classpath

Packages

• A Package is a group of classes available for download and use

• Java’s way of organising classes in different groups..

Packages

• To use a package (other than java.lang) it must be imported into your Java program

• import myPackage.*; //

(saw this with java.io.*;) will make all classes in package myPackage accessible to your class

• import myPackage.class1; will make class1 in package myPackage accessible to your class.

• packages are imported at the top of the source code before any class definitions

• Eclipse takes care of this mostly…

Java packages

• Java Packages available with the JDK

– java.io

– for system input and output

– java.math

– for integer and decimal arithmetic

– java.text

for handling text, dates, numbers…

– java.util

– for collections, date & time facilities...

– java.net

– for implementing networking apps

– java.sql

– for accessing data in a data source

– and many more…

Creating a Package

• Groups of classes which are related can be placed in a package

• Each source file that is to be part of the package must include package packageName; at the start of the source code

• The class files for the package must be placed in a directory with the same name as the package

• Eclipse takes care of this mostly…

Download