50
Lecture 06 Java and OOP Jaeki Song

Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Embed Size (px)

Citation preview

Page 1: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Lecture 06Java and OOP

Jaeki Song

Page 2: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Outlines

• Java and OOP– Class and Object– Inheritance– Polymorphism

Page 3: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Java and OOP: Class

• Classes are the mechanism used to define objects in Java– Objects are instances of classes

• Classes define a “template” for objects, while objects are dynamically created to represent instances of those classes

Page 4: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Examplepublic class Employee { public String firstName; public String lastName; public int employeeNumber; protected float salary;

public Employee (String firstName, String lastName, int empNum, float salary) { this.firstName = firstName; this.lastName = lastName; employeeNumber = empNum; this.salary = salary; }

public float salaryIncrease (int percentageIncrease) { float increase = (float) percentageIncrease / 100; salary += salary * increase; return salary; }

public float getSalary( ) { return salary; }}

Page 5: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Instance Variable vs. Class Variable

• The data items in the class are used as instance variables when an object from the same class is created. These data items are also called state variables. For each object of the class, memory is allocated for these variables.

• If data items or methods in the class are created by the work static, then they are class variables, and memory is allocated to them only once.

Page 6: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

public class Time

{

byte hour;

byte minute;

byte second;

…...

}

Page 7: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Modifiers

• Java provides several modifiers that control access to data, methods, and classes– Public

• Defines classes, methods, and data in such a way that all program can access them

– Private• Defines methods and data in such a way that they

can be accessed by the declaring class but not by any other classes

Page 8: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Accessor Methods

• To make a private data field accessible– get (accessor) method: retrieve data

e.g. getHour( )

– set (mutator) method: modify datae.g. setHour( )

Page 9: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example: get Method

public class Time { private byte hour; private byte minute; private byte second; private byte fPM;

public byte getHour( ) { return hour; }

public byte isPM( ) { return fPM; }}

the returnType is boolean

Page 10: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example: set Method

• Allow code in any class the ability to modify a certain object’s private members

public void setHour (byte newHour) { if (newHour < 0 || newHour > 12 ) return; hour = newHour;}

Page 11: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Constructors

• When an object is created, its member can be initialized by a constructor

• A constructor is a method with the same name as the class– Default constructor initializes the state

variables to zero, false, null, or \000 depending on the type: numerical, boolean, object reference, or char. But, in some objects, the default values would be illegal.

Page 12: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Constructors

• Constructors do not have a return type – not even void

• Constructors are invoked using the new operator when an object is created

Page 13: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Examplepublic class Employee

{

private double salary;

private double fica;

public Employee() //constructor function

{ salary = 0;

fica = 0.06;

}

….

}

Page 14: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Overloading Constructors

• Java allows to overload any method. The condition is that the name of the function, but the number and types of arguments could be different– Same name, same return type, different number

and type of argument

• You can overload the constructor and have as many constructor as you need

Page 15: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example: Overloading Constructors

public class Employee

{

private double salary;

private double fica;

public Employee()

{ salary = 0;

fica = 0.06;

}

public Employee(double sal) // overloaded constructor

{

salary = sal;

fica = 0.06;

}

}

Page 16: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Default Constructor

• If your class does not have a constructor, the compiler creates one for you, and it will not have any argument. However, if you do have a constructor, the compiler will not assign one to you.

• If you have a constructor, but it is not one without argument, the following will not work for you:

Time when = new Time();

Page 17: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Creating Objects

• Java always creates a new object by the new operator

e.g.,

Time when = new Time();

String s = new String(“jaeki”);

Page 18: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Referring to Object’s Variable and Methods

• To access an object’s instance variables and methods, we use the dot operator after the name of the instantiated object.

• In class variables and methods (created by static) the access is via the name of the class with dot operator.

Page 19: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

ExampleExample: class Example uses object Time:

public class Example

{public static void main(String[] args)

{

Time when=new Time();

when.hour = 4;

when.minute = 3;

when.seconds=2;

}

Page 20: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

• Time

Page 21: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Calling the Constructor

• Now, we can create employee two ways:

Employee em = new Employee();

Employee em = new Employee(56500);

• The first new operator calls the first constructor because it does not have any argument, and second calls the constructor that takes one argument.

Page 22: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

• Admission

Page 23: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Life Time of an Object

• The object exists as long as its reference exists

• An object does not exist if there is not reference to it.

Employee em = new Employee();

…..

Em = null; //object now does not exist, it has

// become orphaned object

Page 24: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

When Does an Object Die?

• Local object: when the method goes out of scope.

• Static object: declared as a static member of a class. It remain alive as long as the class is loaded. It dies, when VM dies, unless the reference is made equal to null.

• Instance object: created as a variable within an object class, it dies when the object dies.

Page 25: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Finalizers

• There is no destructor – Every object has an default finalize method that may be

called by the garbage collector.

• One can override it by creating an explicit finalize() method for the object. – The big problem with java is that there is no guaranty

that finalize method will be called by the garbage collector, and the time of it is not clear.

– To enforce its call, use:

System.runFinalizersOnExit(true);

Page 26: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Garbage Collector

• The most important allocated resource in creating objects is memory. Once done, the memory should be released

• Java has automatic garbage collector.

• The garbage collector algorithm has two parts: Mark and Sweep

Page 27: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Releasing Memory Resource

• By making an object reference equal to null, the allocated memory is readied to be released by the garbage collector.

e.g.)Employee myEmp = new Employee()…..myEmp = null; //is ready for garbage collection

//Can call garbage collector by:

System.gc(); //suggests that garbage collector be called

Page 28: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Mark and Sweep

• Mark will follow the object references as well as instance references (object references that are declared as the instance variable within an object), and marks those orphaned objects that have no references

• Sweep releases the objects that are marked back to the heap (heap is the free memory, program stack is the memory allocated to the program.)

Page 29: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Java and OOP: Inheritance

• Java inherits the data and method of another class

Employee

PartTimeEmployee

StudentEmployee

Page 30: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Inheritance

• Inheritance in Java is single inheritance. Multiple inheritance is carried out via Java interfaces.

• “is a” relationship– A PartTimeEmployee “is an” Employee

Employee

PartTime Employee FullTime Employee

Page 31: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Inheritance

Employee

getFname( )

setFname( )

setLname( )

calSalrary( )

PartTime Employee

getFname( )

setFname( )

setLname( )

calSalrary( )

ComputeRate( )

Page 32: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Inheritance

• Inheritance is unidirectional

• Inheritance is transitive

AA

BB

CC

Class B’sParentclass

Class B’schildclass

Class C’sAncestors(or super classes)

Class A’sDescendants(or subclasses)

Page 33: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Inheritance

• Superclass and subclass are relative– extends– implements

class PartTimeEmployee extends Employee

Page 34: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Inheritance in Java: extends

• The key word extends determines the parent a class inherits from.

• A child inherits only from one parent.

• Example

Employee class and PTEmployee class.

public class PTEmployee extends Employee

Page 35: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

ExampleClass PartTimeEmployee extends Employee { public int hoursWorked;

public PartTimeEmployee (String firstName, String lastName, int Num, float sal, int hoursWorked) { super(firstName, lastName, Num, sal); this.hoursWorked = hoursWorked; }

public float getWeeklyWageBill (int hoursWorked) { if (hoursWorked = = 0) return salary * (float) this.hoursWorked; else return salary * (float) hoursWorked; }}

Page 36: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

The protected Modifier

• A protected method in a public class can be accessed by any class in its subclasses

public class C1

protected int x

public class C2 extends C1

x can be read or Modified in C2

public class C3

c1.x cannot be readnor modified

Page 37: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Super Class Call

• In Java, constructors are not inherited, and the child must have its own constructor.– Constructors are not inherited by the child class

• In the constructor of the child, the super class is called: super key world

• Can be used in two ways:– To call a superclass constructor

super ( ), or super (parameters);– To call a superclass method

super.method (parameters);

Page 38: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

public class Employee{

public Employee (String fn, String ln) { fName = fn; lName = ln; }

…….

}

public class PT extends Employee{ public PT (String ln, String fn) { super (ln, fn); percent = 0; hourlyRate = 0; } ……….}

Page 39: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Calling the Super Class Method• In overriding methods, one can call the super

class’s method and then add code to it, if appropriate.

• E.g. public void giveRaise(double r) { super.giveRaise(r); if (hourlyRate > Max_HourlyRate { hourlyRate = Max_HourlyRate;} }

Page 40: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

public float salrayIncrease(int percentageIncrease) { float increase = (float) percentageIncrease / 100; salary = salary * increase; return salary}

salaryIncreased Method in superclass

Method overriding: slarayIncrease method in subclass

public float salrayIncrease(int percentageIncrease) { if (percentIncrease > 5) { percentIncrease = 0 ; } return (super.salaryIncrease(percentIncrease));}

Page 41: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Abstract Class

• A superclass is so abstract that it cannot have any specific instances– Contains many common properties and

behavior

• A method in a abstract class cannot be implemented – The method is implemented in the subclass

Page 42: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Abstract Class

Object GeometricObject

-Color- filled

-getColor- setColor- findArea- findParameter

GeometricObject

-Color- filled

-getColor- setColor- findArea- findParameter

Circle

-radius

-getRadius- setRadius

Circle

-radius

-getRadius- setRadius

Rectangle

-Width- length

-getWidth- setWidth

Rectangle

-Width- length

-getWidth- setWidth

Page 43: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Polymorphism: Upcasting

• All children classes are also of the type of the parent. Therefore one can have:

Employee em = new PTEmployee();– A PTEmployee is a Employee

• The PTEmployee has all of member variables and methods that you’d expect a employee to have

• Assigning the child class to the parent is called upcasting.

Page 44: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Downcasting

• To recover the lost functionality due to upcasting, one can downcast the object:

Employee em = new PTEmployee(“Mary”,”Smith”);

…..

PTEmployee ptem = (PTEmployee) em;

ptem.setPercent(20);

// or

// ((PTEmployee) em).setPercent(20);

Page 45: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Final Method

• To make a class non-virtual, which could not be overridden, the keyword final should be added to the method declaration:

public final void setFName(String fn)

{…

}

Page 46: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example Projects

• Circle

• Admission2

Page 47: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Interfaces

• Multiple inheritance is not supported in java.

• Interface comes close to it.

• An interface is similar to an abstract class that has only public abstract methods.

• Inheritance from an interface is by implements in the class declaration.

Page 48: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Example

public interface wage

{

public abstract void setWage(double h);

}

public class PTEmployee extends Employee implements wage

{….

}

Page 49: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Interface (2)

• A class can implement more than one interface (separate by “,”)

• An interface can inherit other interfaces.

• Interfaces of the base class are inherited by the child class.

Page 50: Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

Interface vs. Abstract Classes

• Interface– Data must be constant

– A method has only a signature without implementation

– Weak “is-kind-of” relationship

e.g. All strings are comparable

• Abstract class– Can have all types of

data

– An abstract class can have concrete methods

– Strong “is a” relationship

e.g. Staff member is a person