object oriented programming with java · object oriented programming with java budditha hettige ....

85
CSC 308 2.0 System Development with Java Budditha Hettige Department of Statistics and Computer Science 1 Object Oriented Programming with Java Budditha Hettige

Upload: others

Post on 07-Jul-2020

26 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

CSC 308 2.0

System Development with Java

Budditha Hettige

Department of Statistics and Computer Science

1

Object Oriented Programming with Java

Budditha Hettige

Page 2: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Advantages of OOP

• Provides a clear modular structure for programs

• OOP makes it easy to maintain and modify existing

code (new objects can be created with small

differences to existing ones)

• OOP provides a good framework for code libraries

• Software components can be easily adapted and

modified by the programmer.

2 Budditha Hettige

Page 3: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Concepts of OOP

• Objects

• Classes

• Data Abstraction

• Encapsulation

• Inheritance

• Polymorphism

3 Budditha Hettige

Page 4: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

What is an Objects?

• Object is a software bundle of related state and

behavior

• Characteristics:

– state and behavior

4 Budditha Hettige

Page 5: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

What is a class?

• A Java class is a group of Java methods and

variables

• Object is an instance of a class

5 Budditha Hettige

Page 6: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Object Oriented Concepts

6 Budditha Hettige

Page 7: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 7

Constructors

• Very similar to C++

• You can create multiple constructors, each must

accept different parameters.

• If you don't write any constructor, the compiler will

(in effect) write one for you:

classname() {}

• If you include any constructors in a class, the

compiler will not create a default constructor!

Page 8: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 8

Multiple Constructors

• One constructor can call another.

• You use "this", not the classname: class Foo {

int i;

Foo() {

this(0);

}

Foo( int x ) {

i = x;

}

A call to this must be the first

statement in the constructor!

Page 9: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 9

Destructors

• No!

• There is a finalize() method that is called

when an object is destroyed.

– you don't have control over when the object is

destroyed (it might never be destroyed).

– The JVM garbage collector takes care of

destroying objects automatically (you have limited

control over this process).

Page 10: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Class Modifiers

• Public

• Abstract

• Final

• Default (none)

10 Budditha Hettige

Page 11: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 11

Class Modifiers

• public: anyone can create an object of the

defined class.

– only one public class per file, must have same

name as the file (this is how Java finds it!).

• default: is non-public (if you don't specify

"public").

Page 12: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 12

Class Modifiers

• Abstract: modifier means that the class can be

used as a superclass only.

– no objects of this class can be created.

• Final: if its definition is complete and no

subclasses are desired or required

– a final class never has any subclasses, the methods

of a final class are never overridden

Page 13: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Field Modifiers

• public

• protected

• private

• none or package or default

• Static

• Final

13 Budditha Hettige

Page 14: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 14

Field Modifiers

• public: any method (in any class) can access the

field.

• protected: any method in the same package can

access the field, or any derived class.

• private: only methods in the class can access the

field.

• Default: is that only methods in the same package

can access the field.

Page 15: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 15

Field Modifiers

• Static: Fields declared static are called class fields (class variables). others are called instance fields. There is only one copy of a static field, no matter how many objects are created.

• Final:class and instance variables (static and non-static fields) may be declared final. The keyword final means: once the value is set, it can never be changed – static final int BUFSIZE=100;

– final double PI=3.14159;

Page 16: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Method Modifiers

• public

• protected

• none or package or default

• private

• final

• abstract

• static

• native

• synchronized

16 Budditha Hettige

Page 17: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 17

Method Modifiers

• private/protected/public:

– same idea as with fields.

• abstract: no implementation given, must be

supplied by subclass.

– the class itself must also be declared abstract

Page 18: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 18

Method Modifiers

• static: the method is a class method, it doesn't depend on any instance fields or methods, and can be called without first creating an object.

• final: the method cannot be changed by a subclass (no alternative implementation can be provided by a subclass).

Page 19: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 19

Method Modifiers

• native: the method is written in some local code (C/C++) - the implementation is not provided in Java.

• synchronized: only one thread at a time can call the method.

Page 20: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 20

Method Overloading

• You can overload methods:

– same method name, different parameters.

– you can't just change return type, the

parameters need to be different.

• Method overloading is resolved at compile

time. int CounterValue() {

return counter;

}

double CounterValue() {

return (double) counter;

}

int CounterValue() {

return counter;

}

double CounterValue() {

return (double) counter;

}

Won't Work!

Page 21: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

All Possible Combinations of Features

and Modifiers

21

Modifier Class Variable Method Constructor

public yes yes yes yes

protected no yes yes yes

None (default) yes yes yes yes

private no yes yes yes

final yes yes yes no

abstract yes no yes no

static no yes yes no

native no no yes no

transient no yes no no

volatile no yes no no

synchronized no no yes no

strictfp yes no yes yes

Budditha Hettige

Page 22: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

22

Modifier Used on Meaning

abstract

Class

Contains unimplemented methods and cannot

be instantiated

interface All interfaces are abstract. Optional in

declarations

method

No body, only signature. The enclosing class is

abstract

Budditha Hettige

Page 23: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

23

Modifier Used on Meaning

Final

Class

Cannot be subclassed

method

Cannot be overridden and dynamically

looked up

field

Cannot change its value. static final

fields are compile-time constants.

variable Cannot change its value.

Budditha Hettige

Page 24: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

24

Modifier Used on Meaning

Native method Platform-dependent. No body, only signature

Modifier Used on Meaning

Private member Accessible only in its class

Modifier Used on Meaning

protected member Accessible only within its package and its subclasses

Budditha Hettige

Page 25: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

25

Modifier Used on Meaning

None

Class Accessible only in its package

Interface Accessible only in its package

Member Accessible only in its package

Budditha Hettige

Page 26: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

26

Modifier Used on Meaning

Public

Class

Accessible anywhere

interface Accessible anywhere

Member

Accessible anywhere.

Budditha Hettige

Page 27: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Java Modifier Summary

27

static

class

method

field

initializer

Make an inner class top-level class

A class method, invoked through the class

name.

A class field, invoked through the class

name

one instance, regardless of class instances

created.

Run when the class is loaded, rather than

when an instance is created.

Budditha Hettige

Page 28: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Packages

28 Budditha Hettige

Page 29: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Package

• defined as a grouping of related types

• existing packages in Java are:

– java.lang - bundles the fundamental classes

– java.io - classes for input , output functions are

bundled in this package

29 Budditha Hettige

Page 30: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Creating a Package

• Put a package statement with the package name

• At the top of every source file that contains the

classes, interfaces, enumerations, and annotation

types that you want to include in the package

• The package statement should be the first line in

the source file

• There can be only one package statement in each

source file, and it applies to all types in the file

30 Budditha Hettige

Page 31: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

/* File name : Animal.java */

package animals;

interface Animal

{

public void eat();

}

package animals;

/* File name : MammalInt.java */

public class Mammal implements Animal

{

public void eat()

{

System.out.println("Mammal eats");

}

Now you compile these two files and put them in a sub-directory called animals

31 Budditha Hettige

Page 32: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

The Import Keyword

• If a class wants to use another class in the same

package, the package name does not need to be

used. Classes in the same package find each other

without any special syntax

• The fully qualified name of the class can be used.

– import animals.Mamal

• The package can be imported using the import

keyword and the wild card (*)

– import animals.*;

32 Budditha Hettige

Page 33: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Abstraction

33 Budditha Hettige

Page 34: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Abstraction

• Refers to the ability to make a class abstract in

OOP

• Abstract class

– Cannot be instantiated

– Other functionality of the class still exists

– Cannot create an instance of the abstract class

34 Budditha Hettige

Page 35: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Abstract Class

• Use the abstract keyword to declare a class

abstract public abstract class Employee

{

private String name;

private String address;

...

}

Cannot use Employee e = new Employee();

35

Employee.java: xx: Employee is abstract; cannot be instantiated Employee e = new Employee(); ^ 1 error1

Employee.java: xx: Employee is abstract; cannot be instantiated Employee e = new Employee(); ^ 1 error1

Budditha Hettige

Page 36: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Extending Abstract Class

public class Salary extends Employee

{

private double salary;

Salary(String name, String address,

int number, double salary)

{

super(name, address, number);

setSalary(salary);

}

...

}

36

Extend Employee class

Extend Employee class

Call Employee class

Budditha Hettige

Page 37: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Abstract Methods

• Can declare the method in the parent class as abstract

• Abstract methods consist of a method signature, but no method body

public abstract class Employee

{

private String name;

private String address;

private int number;

public abstract double computePay();

//Remainder of class definition

}

37 Budditha Hettige

Page 38: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Declaring a Method as Abstract

• The class must also be declared abstract

• Any child class must either override the

abstract method or declare itself abstract

– A child class that inherits an abstract method must

override it

– If they do not, they must be abstract,and any of

their children must override it

38 Budditha Hettige

Page 39: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Salary is Extending Employee class

• it is required to implement computePay() method public class Salary extends Employee

{

private double salary; //Annual salary

public double computePay()

{

System.out.println("Computing " + getName());

return salary/52;

}

//Remainder of class definition

}

39 Budditha Hettige

Page 40: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

40 Budditha Hettige

Page 41: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example(1)

41

Employee -------------

Name

Address Number

computePay() mailCheck()

toString() getName()

Employee -------------

Name

Address Number

computePay() mailCheck()

toString() getName()

Budditha Hettige

Page 42: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Salary class

42

Employee

Salary

Budditha Hettige

Page 43: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Abstract Demonstration

43

Employee

Salary

Budditha Hettige

Page 44: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Exercise

• Remove computePay() methods in the Salary class and re-run the program.

• Change the computePay() as

public abstract double computePay() ;

And re-run the program

• Identify the correct usage of the

– Abstract class

– Abstract methods

44 Budditha Hettige

Page 45: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Encapsulation

45 Budditha Hettige

Page 46: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 46

Encapsulation

• Information Hiding.

• Don't need to know how some component is

implemented to use it.

• Implementation can change without effecting

any calling code.

• "protects us from ourselves"

Page 47: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Encapsulation

• is the technique of making the fields in a class

private and providing access to the fields via

public methods

• is also referred to as data hiding

• Benefit

– is the ability to modify our implemented code without

breaking the code of others who use our code

• Encapsulation gives maintainability, flexibility

and extensibility to our code

47 Budditha Hettige

Page 48: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

public class Encap

{

private String name;

private String idNum;

private int age;

public int getAge()

{

return age;

}

public String getName()

{

return name;

}

48

public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } }

Budditha Hettige

Page 49: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

public class RunEncap

{

public static void main(String args[])

{

EncapTest encap = new EncapTest();

encap.setName("James");

encap.setAge(20);

encap.setIdNum("12343ms");

System.out.println("Name : " + encap.getName()+ " Age : "+ encap.getAge());

}

}

49 Budditha Hettige

Page 50: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Benefits of Encapsulation:

• The fields of a class can be made read-only or

write-only.

• A class can have total control over what is

stored in its fields.

• The users of a class do not know how the class

stores its data. A class can change the data type

of a field, and users of the class do not need to

change any of their code.

50 Budditha Hettige

Page 51: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Inheritance

51 Budditha Hettige

Page 52: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 52

Inheritance

• On the surface, inheritance is a code re-use

issue.

– we can extend code that is already written in a

manageable manner.

• Inheritance is more, it supports polymorphism

at the language level!

• Information is made manageable in a

hierarchical order

Page 53: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Inheritance cont.

• With Inheritance, new class can be derived from existing classes as a building block

• New class Inherit properties and methods from the existing class

• New class can also added Its own properties and methods

• Keyword

– Extends

– Implements

53 Budditha Hettige

Page 54: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 54

Inheritance cont.

• Take an existing object type (collection of fields and methods) and extend it.

– create a special version of the code without re-writing any of the existing code (or even explicitly calling it!).

– End result is a more specific object type, called the sub-class / derived class / child class.

– The original code is called the super class / parent class / base class.

Page 55: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

IS-A Relationship (Example)

public class Animal

{

}

public class Mammal extends Animal

{ }

public class Reptile extends Animal

{ }

public class Dog extends Mammal

{ }

55

Animal

Mamal

extends

Budditha Hettige

Page 56: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

IS-A Relationship (Example)

public class Dog extends Mammal

{

public static void main(String args[])

{

Animal a = new Animal();

Reptile r = new Reptile();

Mammal m = new Mammal();

Dog d = new Dog();

System.out.println(m instanceof Animal);

System.out.println(d instanceof Mammal);

System.out.println(d instanceof Animal);

}

}

56

Animal

Mamal Dog Reptile

Budditha Hettige

Page 57: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

IS-A Relationship

• In Object Oriented terms following are true:

– Animal is the superclass of Mammal class.

– Animal is the superclass of Reptile class.

– Mammal and Reptile are sub classes of Animal

class.

– Dog is the subclass of both Mammal and Animal

classes.

57 Budditha Hettige

Page 58: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

IS-A Relationship

• IS-A relationship we can say:

– Mammal IS-A Animal

– Reptile IS-A Animal

– Dog IS-A Mammal

– Hence : Dog IS-A Animal as well

• Use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass

58 Budditha Hettige

Page 59: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 59

Accessing superclass methods

• Can use super() to access all (non-private)

superclass methods.

– even those replaced with new versions in the

derived class.

• Can use super() to call base class

constructor.

Page 60: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 60

Single Inheritance

• You can't extend more than one class!

– the derived class can't have more than one base

class.

• You can do multiple inheritance with interface

inheritance.

Page 61: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 61

Inheritance Example cont.

• Employee: name, email, phone

– FulltimeEmployee: also has salary, office, benefits, …

• Manager: CompanyCar, can change salaries, rates contracts,

offices, etc.

– Contractor: HourlyRate, ContractDuration, …

• A manager a special kind of FullTimeEmployee,

which is a special kind of Employee.

• The relationship modeled by inheritance is often

referred to as a “is a” relationship

Page 62: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Inheritance Example

62

Employee ------------------ Name Email Phone

Employee ------------------ Name Email Phone

FulltimeEmployee ------------------------ Salary Office

FulltimeEmployee ------------------------ Salary Office

Manager ------------------ CompanyCar Email Phone

Manager ------------------ CompanyCar Email Phone

Contractor ------------------ HourlyRate, ContractDuration

Contractor ------------------ HourlyRate, ContractDuration

Budditha Hettige

Page 63: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Inheritance Example

63

Employee ------------------ Name Email Phone

Employee ------------------ Name Email Phone

FulltimeEmployee ------------------------ Salary Office

FulltimeEmployee ------------------------ Salary Office

Manager ------------------ CompanyCar Email Phone

Manager ------------------ CompanyCar Email Phone

Contractor ------------------ HourlyRate, ContractDuration

Contractor ------------------ HourlyRate, ContractDuration

Is a

Is a Is a

Budditha Hettige

Page 64: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Inheritance Example

• Manager is a full time employee

• Full time employee is a employee

64 Budditha Hettige

Page 65: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

HAS-A Relationship

• relationships are mainly based on the usage

• determines whether a certain class HAS-A

certain thing

• helps to reduce duplication of code as well as

bugs

65 Budditha Hettige

Page 66: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

public class Vehicle

{}

public class Speed

{}

public class Van extends Vehicle

{

private Speed sp;

}

• class Van HAS-A Speed

– Reuse the Speed class in multiple applications

66

Vehicle

Van

Van sp sp

Budditha Hettige

Page 67: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Interface

67 Budditha Hettige

Page 68: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 68

Interfaces

• is a collection of abstract methods

• An interface is not a class

– A class describes the attributes and behaviors of an

object

– An interface contains behaviors that a class

implements

Page 69: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Interfaces cont.

• Interfaces have the following properties:

– An interface is implicitly abstract. You do not need

to use the abstract keyword when declaring an

interface.

– Methods in an interface are implicitly public.

69 Budditha Hettige

Page 70: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Interfaces cont.

• An interface is a definition of method

prototypes and possibly some constants (static

final fields).

• An interface does not include the

implementation of any methods, it just defines

a set of methods that could be implemented.

70 Budditha Hettige

Page 71: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 71

Implement an interfaces

• A class can implement an interface, this

means that it provides implementations for all

the methods in the interface.

• Java classes can implement any number of

interfaces (multiple interface inheritance).

Page 72: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 72

Interfaces

• Creation (definition) of interfaces can be done using inheritance:

– one interface can extend another.

• Sometimes interfaces are used just as labeling mechanisms:

– Look in the Java API documentation for interfaces like Cloneable.

Page 73: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Interfaces

• An interface is similar to a class in the following

ways:

– An interface can contain any number of methods.

– An interface is written in a file with a .java extension,

with the name of the interface matching the name of

the file.

– The bytecode of an interface appears in a .class file.

– Interfaces appear in packages, and their corresponding

bytecode file must be in a directory structure that

matches the package name.

73 Budditha Hettige

Page 74: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Interfaces

• An interface is different from a class in several ways, including: – You cannot instantiate an interface.

– An interface does not contain any constructors.

– All of the methods in an interface are abstract.

– An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

– An interface is not extended by a class; it is implemented by a class.

– An interface can extend multiple interfaces.

74 Budditha Hettige

Page 75: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Declaring Interfaces

• The interface keyword is used to declare an interface public class MammalInt implements Animal

{

public void eat()

{

System.out.println("Mammal eats");

}

public static void main(String args[])

{

MammalInt m = new MammalInt();

m.eat();

}

}

75

interface Animal { public void eat(); }

interface Animal { public void eat(); }

Budditha Hettige

Page 76: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Extending Interfaces

• An interface can extend another interface public interface Sports

{

public void setHomeTeam(String name);

}

public interface Football extends Sports

{

public void homeTeamScored(int points);

}

public interface Hockey extends Sports

{

public void homeGoalScored();

}

76

Sport

Football Hockey

Budditha Hettige

Page 77: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Multiple Interfaces

• A Java class can only extend one parent class.

• Multiple inheritance is not allowed

• An interface can extend more than one parent

interface

• Extends keyword is used once, and the parent

interfaces are declared in a comma-separated list.

– public interface Hockey extends Sports, Event

77 Hockey

Sports Event

Budditha Hettige

Page 78: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

The “instanceof” Keyword

• the instanceof operator to check determine

whether Mammal is actually an Animal, and

dog is actually an Animal

78 Budditha Hettige

Page 79: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Polymorphism

79 Budditha Hettige

Page 80: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Polymorphism

• is the ability of an object to take on many

forms

• OOP occurs when a parent class reference is

used to refer to a child class object

80 Budditha Hettige

Page 81: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 81

Polymorphism

• Create code that deals with general object

types, without the need to know what specific

type each object is.

• Generate a list of employee names:

– all objects derived from Employee have a name

field!

– no need to treat managers differently from anyone

else.

Page 82: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Budditha Hettige 82

Polymorphism

• The real power comes with methods/behaviors.

• A better example:

– shape object types used by a drawing program.

– we want to be able to handle any kind of shape someone wants to code (in the future).

– we want to be able to write code now that can deal with shape objects (without knowing what they are!).

Page 83: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

public interface Vegetarian {}

public class Animal{}

public class Deer extends Animal implements Vegetarian{}

• Deer class is considered to be polymorphic since this has

multiple inheritance

– A Deer IS-A aAnimal

– A Deer IS-A Vegetarian

– A Deer IS-A Deer

– A Deer IS-A Object

83 Budditha Hettige

Page 84: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Types of Polymorphism

• Overloading

• Overriding

• Dynamic method binding

84 Budditha Hettige

Page 85: Object Oriented Programming with Java · Object Oriented Programming with Java Budditha Hettige . Advantages of OOP •Provides a clear modular structure for programs •OOP makes

Example

public static void main ( String ary[ ] )

{

Box x;

Box b1 =new Box( );

WoddenBox wb=new WoddenBox( );

SteelBox s1=new SteelBox( );

LargeWoddenBox p1=new LargeWoddenBox( );

b1.info( );

wb.info( );

s1.info( );

p1.info( );

System.out.println("-------------------------");

Box b[]=new Box[5];

b[1]=new Box();

b[2]=new WoddenBox();

b[3]=new SteelBox();

b[4]=new LargeWoddenBox();

for(int i=1;i<5;i++)

b[i].info();

}

85

Box

WoddenBox SteelBox

LargeWoddenBox

Budditha Hettige