OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Similar documents
Inheritance. The Java Platform Class Hierarchy

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

What is Inheritance?

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Subclasses, Superclasses, and Inheritance

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

CS260 Intro to Java & Android 03.Java Language Basics

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

INHERITANCE. Spring 2019

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Abstract Classes and Interfaces

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

UCLA PIC 20A Java Programming

Polymorphism. return a.doublevalue() + b.doublevalue();

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Lecture 2: Java & Javadoc

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Java Magistère BFA

Computer Science 210: Data Structures

CLASS DESIGN. Objectives MODULE 4

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Introduction to Inheritance

CS-202 Introduction to Object Oriented Programming

Inheritance (continued) Inheritance

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Java Object Oriented Design. CSC207 Fall 2014

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Inheritance and Polymorphism

Java Fundamentals (II)

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 5 Object-Oriented Programming

Super-Classes and sub-classes

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Inheritance (Part 5) Odds and ends

CS 251 Intermediate Programming Inheritance

ITI Introduction to Computing II

OVERRIDING. 7/11/2015 Budditha Hettige 82

ITI Introduction to Computing II

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance. Transitivity

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

15CS45 : OBJECT ORIENTED CONCEPTS

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

More On inheritance. What you can do in subclass regarding methods:

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CH. 2 OBJECT-ORIENTED PROGRAMMING

1 Shyam sir JAVA Notes

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

CMSC 132: Object-Oriented Programming II

Example: Count of Points

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Building Java Programs. Inheritance and Polymorphism

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Polymorphism and Interfaces. CGS 3416 Spring 2018

Programming II (CS300)

EXERCISES SOFTWARE DEVELOPMENT I. 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W

Programming overview

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance (Outsource: )

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Class, Variable, Constructor, Object, Method Questions

Programming II (CS300)

CSC 1214: Object-Oriented Programming

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

25. Generic Programming

Inheritance Inheritance 3/3/2014. We have already seen. Object Oriented Programming: Inheritance (Chapter 9) Abstractions

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Lecture Notes Chapter #9_b Inheritance & Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Modern Programming Languages. Lecture Java Programming Language. An Introduction

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Practice for Chapter 11

Exercise: Singleton 1

OBJECT ORİENTATİON ENCAPSULATİON

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

F I N A L E X A M I N A T I O N

Inheritance Motivation

Object-Oriented Concepts

Object Oriented Programming. Java-Lecture 11 Polymorphism

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Lecture 4: Extending Classes. Concept

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Classes and Inheritance Extending Classes, Chapter 5.2

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Rules and syntax for inheritance. The boring stuff

First IS-A Relationship: Inheritance

OBJECT 1 ORIENTED PROGRAMMING

Unit 4 - Inheritance, Packages & Interfaces

Full file at Chapter 2 - Inheritance and Exception Handling

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

More Relationships Between Classes

Transcription:

OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616

Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Descendent a class derived from other class

Inheritance Every class has one and only one direct superclass (single inheritance). A subclass inherits all the members (fields, methods, and nested classes) from its superclass The constructor of the superclass is not inherited but can be invoked from the subclass

Inheritance

Inheritance

The Java Platform Class Hierarchy Every class is implicitly a subclass of Object (java.lang package) Defines and implements behavior common to all classes Hierarchy of classes http://java.sun.com/javase/6/docs/api/java/lang/obj ect.html

The Java Platform Class Hierarchy

Inheritance - example class Polygon { protected double[ ] sides; public Polygon(int n) { sides = new double[n]; } public double perimeter( ) { double s=0; for(int i=0;i<sides.length;i++) s+=sides[i]; return s; }}

Inheritance - example class Rectangle extends Polygon { public Rectangle(double L, double h){ super(4); sides[0] = sides[2] = L; sides[1] = sides[3] = h; } public double area( ){ return sides[0]*sides[1]; }}

Inheritance - example class Client { public static void main (String [] args){ Rectangle r1 = new Rectangle (4, 2); } } System.out.println( The perimeter is: + r1.perimeter(); System.out.println( The area is: + r1.area();

Inheritance

Subclasses Inherits all of the public and protected members of its parent, no matter what package the subclass is in In the same package as its parent, it inherits the package-private members of the parent The inherited fields and methods can be used directly Can declare a field in the subclass with the same name as the one in the superclass hiding it

Subclasses

Subclasses Can have new fields and new methods Create a new instance method in the subclass that has the same signature as the one in the superclass overriding Create a new static method in the subclass that has the same signature as the one in the superclass hiding Does not inherit the private members of its parent class accessed only if the superclass has public or protected methods Write a subclass constructor that invokes the constructor of the superclass

Casting objects Rectangle rt = new Rectangle(2,3); Rectangle Polygon Object rt is a Rectangle, a Polygon, and an Object Casting shows the use of an object of one type in place of another type (permitted by inheritance and implementations) Object obj = new Rectangle(2,3); implicit casting

Casting objects Rectangle rt = obj; compile-time error Rectangle rt = (Rectangle) obj; explicit casting the instanceof operator a logical test to the type of a particular object if (obj instanceof Rectangle) {Rectangle rt = (Rectangle) obj; }

Overriding and Hiding Methods Instance Methods An instance method in a subclass with the same signature as an instance method in the superclass overrides the superclass's method. Allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed

Overriding and Hiding Methods

Overriding and Hiding Methods Class Methods If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding: The version of the overridden method that gets invoked is the one in the subclass The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

Overriding and Hiding Methods public class Animal { } public static void testclassmethod() { } System.out.println("The class method in Animal."); public void testinstancemethod() { } System.out.println("The instance method in Animal.");

Overriding and Hiding Methods public class Cat extends Animal { } public static void testclassmethod() { } System.out.println("The class method in Cat."); public void testinstancemethod() { } System.out.println("The instance method in Cat.");

Overriding and Hiding Methods public class Client{ public static void main(string[ ] args) { Cat mycat = new Cat(); Animal myanimal = mycat; Animal.testClassMethod(); myanimal.testinstancemethod(); }} The output: The class method in Animal. -- hidden The instance method in Cat. -- overrided

Overriding and Hiding Methods

Overriding and Hiding Methods

Overriding and Hiding Methods Modifiers The access modifier for an overriding method can allow more, but not less, access than the overridden method Cannot change an instance method in the superclass to a class method in the subclass, and vice versa

Overriding and overloading Override a method having the same signature (name, plus the number and the type of its parameters) and return type into a subclass Overload a method having the same name and return type but different list of parameters in the same class

Using the keyword super

Using the keyword super Used to invoke the superclass s members public class Superclass { public void printmethod() { System.out.println("Printed in Superclass."); }} public class Subclass extends Superclass { public void printmethod(){ }} super.printmethod(); System.out.println("Printed in Subclass");

Using the keyword super public class Client{ public static void main(string[] args) { Subclass s = new Subclass(); s.printmethod(); } } The output: Printed in Superclass. Printed in Subclass

Using the keyword super

Subclass constructors public Rectangle(double L, double h){ super(4); sides[0] = sides[2] = L; sides[1] = sides[3] = h;} The invocation of a superclass constructor must be the first line in the subclass constructor. The syntax for calling a superclass constructor: super() or super(parameter list)

Subclass constructors

Problem Create a class to describe a company s employees. The class should have a method to compute the salary based on the number of worked hours. Create a different class to describe the manager and override the salary method.

Solution public class Employee{ private String name, address; private double hour_wage; public Employee(String n, String a, double p){ name = n; address = a; hour_wage = p;} public double computesal(int nr){ return (hour_wage*nr);} public void printdata(int nr){ System.out.printf("%s worked %d hours and earned %f RON",name, nr, computesal(nr));} }

Solution public class Manager extends Employee{ private double manag_all; } public Manager(String n, String a, double p, double al){ super(n, a, p); manag_all = al;} public double computesal(int nr){ return (1+ manag_all/100)*super.computesal(nr));}

Solution public class Client{ public static void main (String [] arg) throws IOException { BufferedReader r_in = new BufferedReader(new InputStreamReader (System.in)); Employee e1 = new Employee( Al Bundy", "LA", 15.0); Employee e2 = new Manager( Seifeld", "NY",20.0, 30.0); System.out.println( How many hours? "); int h=integer.parseint(r_in.readline()); e1.printdata(h); e2.printdata(h); r_in.close();}

Object as Superclass Every class is a descendant, direct or indirect protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object. public boolean equals(object obj) Indicates whether some other object is "equal to" this one.

Object as Superclass protected void finalize() throws Throwable Called by the garbage collector on an object public final Class getclass() Returns the runtime class of an object. public int hashcode() Returns a hash code value for the object. public String tostring() Returns a string representation of the object.

Object as Superclass Synchronizing the activities of independently running threads in a program public final void notify() public final void notifyall() public final void wait() public final void wait(long timeout) public final void wait(long timeout, int nanos)

The clone() Method A class, or one of its superclasses, implements the Cloneable interface acloneableobject.clone(); protected Object clone() throws CloneNotSupportedException public Object clone() throws CloneNotSupportedException Add implements Cloneable to your class's declaration

The equals() Method Compares two objects for equality and returns true if they are equal public class Book { }... public boolean equals(object obj) { } if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false;

The equals() Method Book firstbook = new Book("0201914670"); Book secondbook = new Book("0201914670"); if (firstbook.equals(secondbook)) else System.out.println("objects are equal"); System.out.println("objects are not equal"); The output: objects are equal

The finalize() Method May be invoked on an object when it becomes garbage class MyClass{ private long a; public MyClass(long x){ a=x; System.out.println( Object +a+ was created );} protected void finalize() throws Throwable{ } System.out.println( Object +a+ was destroyed );}

The finalize() Method class ClientClass{ public static void main (String [ ] args){ MyClass a; long no_obj = 50000; for( long i=4;i<no_obj;i++) { a=new MyClass(i); a=null;} }

The getclass() Method You cannot override getclass() Returns a Class object, which has methods you can use to get information about the class: Its name (getsimplename()) its superclass (getsuperclass()) the interfaces it implements (getinterfaces()) void printclassname(object obj) { System.out.println("The object's class is + obj.getclass().getsimplename());} http://java.sun.com/javase/6/docs/api/java/lang /Class.html

Writing Final Classes and Methods Indicate that the method cannot be overridden by subclasses class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK }... final ChessPlayer getfirstplayer() {...} return ChessPlayer.WHITE; } An entire class final when creating an immutable class like the String class

Abstract Methods and Classes An abstract class: a class that is declared abstract cannot be instantiated, but they can be inherited An abstract method a method that is declared without an implementation abstract void moveto(double deltax, double deltay); If a class includes abstract methods, the class itself must be declared abstract

Abstract Methods and Classes public abstract class GraphicObject { } // declare fields // declare non-abstract methods abstract void draw(); The subclass has to provide implementations for all of the abstract methods abstract

Abstract Methods and Classes

Abstract Methods and Classes Graphic objects: states (for example: position, orientation, line color, fill color) behaviors (for example: moveto, rotate, resize, draw)

Abstract Methods and Classes abstract class GraphicObject { int x, y;... void moveto(int newx, int newy) {... } abstract void draw(); abstract void resize(); }

Abstract Methods and Classes class Circle extends GraphicObject { void draw() {... } void resize() {... } } class Rectangle extends GraphicObject { void draw() {... } void resize() {... } }

Abstract Methods and Classes

What Is Polymorphism? The ability of one object to be treated, or used, like another A powerful tool allowing architectures to be: designed and built that will be flexible enough to change with businesses' needs, stable enough not to require redesign and rebuild on a regular basis

Overloading (parametric) polymorphism A class or classes implement methods that are the same in signature except for the parameters passed to the method One class can handle many different types of arguments to a specific method public void draw(int i){ } public void draw(double d){ } public void draw(char c){ }

Overriding polymorphism Occurs when a child class overrides the method implementation of the parent class Different child classes have different behaviors based on some intrinsic characteristic of the child class public class Drink{ } public void ingest() { }

Overriding polymorphism public class Milk extends Drink{ public void ingest() {//action specific} } public class Vodka extends Drink{ public void ingest() {//action specific} }

Polymorphism

Inclusion polymorphism A child class inherits its method substance from the base or parent class Enables objects or systems that would previously have used the base class to use the child classes with equivalent results

Coercion polymorphism A primitive or object type is cast or "coerced" into being another primitive type or object type Rectangle rt = (Rectangle) obj; float f = 3.4; int I = (int) f;

Problem Create an abstract class to describe a bank account. There can be only two types: RON and EUR accounts. One can make the following operations: depose, extract, and transfer money between two accounts of the same type. An owner will receive an interest which computes as follows: 0.03 of deposit for EUR account 0.06 of deposit for RON account Override equals() and tostring() methods.

Solution public abstract class Account{ private double sum; public Account(double s){ sum = s;} public void depose(double s){ sum+=s;} public void extract(double s){ sum-=s;} public double getsum(){ return sum;}

Solution abstract public double interest(); abstract public void transfer(account a, double s); public boolean equals(account a) { } if (sum==a.sum) return true; else return false;} public String tostring(){ return String.format("The account's sum is %6.2f",sum);}

Solution public class RonAcc extends Account{ public RonAcc(double s){ super(s);} public double interest(){ return 0.05*getSum();} public void totalamount(){ depose(interest());} public void transfer(account a, double s){ if(a instanceof RonAcc) {this.extract(s); a.depose(s);} else System.out.println("Account mismatch");} }

Solution public class EurAcc extends Account{ public EurAcc(double s){ super(s);} public double interest(){ return 0.03*getSum();} public void totalamount(){ depose(interest());} public void transfer(account a, double s){ if(a instanceof EurAcc) {this.extract(s); a.depose(s);} else System.out.println("Account mismatch");} }

Solution import java.io.*; public class ClientAcc{ public static void main (String [] arg) throws IOException { BufferedReader r_in = new BufferedReader(new InputStreamReader (System.in)); System.out.println("How much money is in Ron account?"); Account a1 = new RonAcc(Double.parseDouble(r_in.readLine())); System.out.println("How much money is in EUR account?"); Account a2 = new EURAcc(Double.parseDouble(r_in.readLine()));

Solution ((RonAcc) a1).totalamount(); System.out.println(a1); ((EURAcc) a2).totalamount(); System.out.println(a2); ((RonAcc) a1).transfer(a2,10.2); r_in.close();} }

References The Java Tutorials. Learning the Java Language. http://java.sun.com/docs/books/tutorial/java/ia ndi/subclasses.html The Power of Polymorphism, http://www2.syscon.com/itsg/virtualcd/java/archives/0508/barn abee/index.html