+ All Categories
Home > Documents > Object Oriented Concepts in Java

Object Oriented Concepts in Java

Date post: 24-Feb-2016
Category:
Upload: dasha
View: 47 times
Download: 0 times
Share this document with a friend
Description:
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; - PowerPoint PPT Presentation
Popular Tags:
39
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism slide covered in class – others for re
Transcript
Page 1: Object Oriented Concepts in Java

Object Oriented Concepts in Java

ObjectsInheritance

EncapsulationPolymorphism

= slide covered in class – others for reference

Page 2: Object Oriented Concepts in Java

Sample class…public class Bicycle { public int cadence; public int gear; public int speed;

public Bicycle(int startCadence, int startSpeed, int startGear) { 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..indentationBrackets { }Java wordsCase conventions ..

Page 3: Object Oriented Concepts in Java

public class Bicycle {

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

// the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }

// 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; }

}

Comments in your code

// ALWAYS comment your code// each method // each attribute..

Comments

Page 4: Object Oriented Concepts in Java

Class vs Instance Objects

• Class members– class fields– class methods

• Instance members– instance fields– instance methods

Page 5: Object Oriented Concepts in Java

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

Page 6: Object Oriented Concepts in Java

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

constantstatic 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

Page 7: Object Oriented Concepts in Java

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 namedouble avgAtt = MyUtils.mean(attendance);

Page 8: Object Oriented Concepts in Java

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

Page 9: Object Oriented Concepts in Java

Example – class vs instance

public class BankAccount{// instance fieldsString name;double balance;// class fieldstatic double interestRate;// instance methodpublic double getBalance(){

return balance;}// class methodpublic static double getRate(){

return interestRate;}...

}

Page 10: Object Oriented Concepts in Java

Example – class vs instance

• Code to setup and use BankAccounts//instantiate a BankAccountBankAccount myAcc = new BankAccount(...);

// access its instance field balanceSystem.out.println(myAcc.getBalance());

// access its class field interestRateSystem.out.println(BankAccount.interestRate);

default constructor

Class name

Page 11: Object Oriented Concepts in Java

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 constructorsBankAccount(String name){

this.name=name;this.balance=0;

}BankAccount(String name, double balance){

this.name=name;this.balance=balance;

};

Page 12: Object Oriented Concepts in Java

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?

Page 13: Object Oriented Concepts in Java

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

Page 14: Object Oriented Concepts in Java

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

Page 15: Object Oriented Concepts in Java

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

Page 16: Object Oriented Concepts in Java

super Examplepublic 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 yrspublic LoanAccount(name, amt, period){

super(name);this.loanAmount=amt;this.loanPeriod=period;

}...}

Page 17: Object Oriented Concepts in Java

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

Page 18: Object Oriented Concepts in Java

public final class MyFinalClass { ..}

public class NotAllowed extends MyFinalClass {...} // forbidden

Points about Inheritance

Page 19: Object Oriented Concepts in Java

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 castBankAccount myAcc = new BankAccount(…); //superclassLoanAccount myLoan = new LoanAccount(…); //subclassmyAcc = myLoan; // OK assign subclass to superclassmyLoan = myAcc // not OK why not?myLoan = (LoanAccount) myAcc; // OKif(myAcc instanceOf LoanAccount)

LoanAccount myLoan = (LoanAccount) myAcc; // better

Page 20: Object Oriented Concepts in Java

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?

Page 21: Object Oriented Concepts in Java

class Animal{

public void move(){ System.out.println("Animals can move"); }}

class Dog extends Animal{

public void move(){ System.out.println("Dogs can walk and run"); }}

public class TestDog{

public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object 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 }}

The benefit of overriding is: ability to define a behavior that's specific to the sub class type.

In OO terms, overriding means to override the functionality of any existing method.

Page 22: Object Oriented Concepts in Java

toString()

• Example - toString() method - • The root Object class has a toString() method which

allows an object of the class to be output as a stringpublic 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

Page 23: Object Oriented Concepts in Java

Overriding example

public class BankAccount {public String toString(){

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

}}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;

}}

What happens if you don’t override the toString() method?

Page 24: Object Oriented Concepts in Java

super

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

// Bank Account toString methodpublic String toString(){

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

}// Loan Account toString methodpublic String toString(){

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

}

Page 25: Object Oriented Concepts in Java

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()

Page 26: Object Oriented Concepts in Java

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 OverloadingOverloading does not use dynamic binding (because overloading is understood at compile time.)

Page 27: Object Oriented Concepts in Java

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

Page 28: Object Oriented Concepts in Java

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…

Page 29: Object Oriented Concepts in Java

Polymorphism example

abstract class Account {

int balance;   abstract void withdraw(int amount);

}  

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 */ }

}

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

Page 30: Object Oriented Concepts in Java

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..

Page 31: Object Oriented Concepts in Java

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”…

Page 32: Object Oriented Concepts in Java

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).

Page 33: Object Oriented Concepts in Java

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

Page 34: Object Oriented Concepts in Java

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)

Page 35: Object Oriented Concepts in Java

Java Packages& Classpath

Page 36: Object Oriented Concepts in Java

Packages

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

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

Page 37: Object Oriented Concepts in Java

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…

Page 38: Object Oriented Concepts in Java

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…

Page 39: Object Oriented Concepts in Java

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…


Recommended