Lecture Note

Download Report

Transcript Lecture Note

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
Example
public 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;
}
}
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.
Example
public class Time
{
byte hour;
byte minute;
byte second;
…...
}
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
Accessor Methods
• To make a private data field accessible
– get (accessor) method: retrieve data
e.g. getHour( )
– set (mutator) method: modify data
e.g. setHour( )
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
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;
}
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.
Constructors
• Constructors do not have a return type – not
even void
• Constructors are invoked using the new
operator when an object is created
Example
public class Employee
{
private double salary;
private double fica;
public Employee()
{ salary = 0;
fica = 0.06;
}
….
}
//constructor function
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
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;
}
}
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();
Creating Objects
• Java always creates a new object by the
new operator
e.g.,
Time when = new Time();
String s = new String(“jaeki”);
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.
Example
Example: 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;
}
Example
• Time
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.
Example
• Admission
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
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.
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);
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
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
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.)
Java and OOP: Inheritance
• Java inherits the data and method of another
class
Employee
PartTimeEmployee
StudentEmployee
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
Inheritance
Employee
PartTime Employee
getFname( )
getFname( )
setFname( )
setFname( )
setLname( )
setLname( )
calSalrary( )
calSalrary( )
ComputeRate( )
Inheritance
• Inheritance is
unidirectional
• Inheritance is
transitive
Class B’s
Parent
class
Class C’s
Ancestors
(or super
classes)
A
B
Class B’s
child
class
Class A’s
Descendants
(or subclasses)
C
Inheritance
• Superclass and subclass are relative
– extends
– implements
class PartTimeEmployee extends Employee
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
Example
Class 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;
}
}
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 read
nor modified
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);
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;
}
……….
}
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;}
}
Example
salaryIncreased Method in superclass
public float salrayIncrease(int percentageIncrease) {
float increase = (float) percentageIncrease / 100;
salary = salary * increase;
return salary
}
Method overriding: slarayIncrease method in subclass
public float salrayIncrease(int percentageIncrease) {
if (percentIncrease > 5)
{ percentIncrease = 0 ; }
return (super.salaryIncrease(percentIncrease));
}
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
Abstract Class
Circle
Object
GeometricObject
-Color
- filled
-getColor
- setColor
- findArea
- findParameter
-radius
-getRadius
- setRadius
Rectangle
-Width
- length
-getWidth
- setWidth
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.
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);
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)
{…
}
Example Projects
• Circle
• Admission2
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.
Example
public interface wage
{
public abstract void setWage(double h);
}
public class PTEmployee extends Employee
implements wage
{….
}
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.
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