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

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
Python Objects and Classes
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
OOP: Inheritance By: Lamiaa Said.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Programming Languages and Paradigms Object-Oriented Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Inheritance and Polymorphism
OOP’S Concepts in C#.Net
Java Programming Language
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Chapter 8 Class Inheritance and Interfaces
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

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 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() //constructor function { salary = 0; fica = 0.06; } …. }

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 PartTimeEmployeeStudentEmployee

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

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

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)

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

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

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