Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism."— Presentation transcript:

1 Lecture 06 Java and OOP Jaeki Song

2 Outlines Java and OOP –Class and Object – Inheritance – Polymorphism

3 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

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

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

6 Example public class Time { byte hour; byte minute; byte second; …... }

7 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

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

9 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

10 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 12 ) return; hour = newHour; }

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

12 Constructors Constructors do not have a return type – not even void Constructors are invoked using the new operator when an object is created

13 Example public class Employee { private double salary; private double fica; public Employee() //constructor function { salary = 0; fica = 0.06; } …. }

14 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

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

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

17 Creating Objects Java always creates a new object by the new operator e.g., Time when = new Time(); String s = new String(“jaeki”);

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

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

20 Example Time

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

22 Example Admission

23 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

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

25 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);

26 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

27 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

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

29 Java and OOP: Inheritance Java inherits the data and method of another class Employee PartTimeEmployeeStudentEmployee

30 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 EmployeeFullTime Employee

31 Inheritance Employee getFname( ) setFname( ) setLname( ) calSalrary( ) PartTime Employee getFname( ) setFname( ) setLname( ) calSalrary( ) ComputeRate( )

32 Inheritance Inheritance is unidirectional Inheritance is transitive A A B B C C Class B’s Parent class Class B’s child class Class C’s Ancestors (or super classes) Class A’s Descendants (or subclasses)

33 Inheritance Superclass and subclass are relative –extends –implements class PartTimeEmployee extends Employee

34 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

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

36 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

37 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);

38 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; } ………. }

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

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

41 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

42 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

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

44 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);

45 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) {… }

46 Example Projects Circle Admission2

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

48 Example public interface wage { public abstract void setWage(double h); } public class PTEmployee extends Employee implements wage {…. }

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

50 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


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

Similar presentations


Ads by Google