OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Size: px
Start display at page:

Download "OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616"

Transcription

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

2 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

3 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

4 Inheritance

5 Inheritance

6 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 ect.html

7 The Java Platform Class Hierarchy

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

9 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]; }}

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

11 Inheritance

12 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

13 Subclasses

14 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

15 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

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

17 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

18 Overriding and Hiding Methods

19 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

20 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.");

21 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.");

22 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

23 Overriding and Hiding Methods

24 Overriding and Hiding Methods

25 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

26 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

27 Using the keyword super

28 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");

29 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

30 Using the keyword super

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

32 Subclass constructors

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

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

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

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

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

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

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

40 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

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

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

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

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

45 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());} /Class.html

46 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

47 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

48 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

49 Abstract Methods and Classes

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

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

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

53 Abstract Methods and Classes

54 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

55 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){ }

56 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() { }

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

58 Polymorphism

59 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

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

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

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

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

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

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

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

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

68 References The Java Tutorials. Learning the Java Language. ndi/subclasses.html The Power of Polymorphism, abee/index.html

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

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

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) (SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) Dongwon Jeong djeong@kunsan.ac.kr; http://ist.kunsan.ac.kr/ Information Sciences and Technology Laboratory, Dept. of

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Subclasses, Superclasses, and Inheritance

Subclasses, Superclasses, and Inheritance Subclasses, Superclasses, and Inheritance To recap what you've seen before, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass.

More information

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

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass? COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

UCLA PIC 20A Java Programming

UCLA PIC 20A Java Programming UCLA PIC 20A Java Programming Instructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing Teaching Assistant: Yon Seo Kim, PIC Chapter 5 Classes & Inheritance Creating Classes

More information

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

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

Computer Science 210: Data Structures

Computer Science 210: Data Structures Computer Science 210: Data Structures Summary Today writing a Java program guidelines on clear code object-oriented design inheritance polymorphism this exceptions interfaces READING: GT chapter 2 Object-Oriented

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

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

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

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

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

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

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

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

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

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

S.E. Sem. III [CMPN] Object Oriented Programming Methodology S.E. Sem. III [CMPN] Object Oriented Programming Methodology Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 80 Q.1(a) Write a program to calculate GCD of two numbers in java. [5] (A) import java.util.*;

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

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

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

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)

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) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Polymorphism and Interfaces. CGS 3416 Spring 2018

Polymorphism and Interfaces. CGS 3416 Spring 2018 Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

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

EXERCISES SOFTWARE DEVELOPMENT I. 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W EXERCISES SOFTWARE DEVELOPMENT I 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W Inheritance I INHERITANCE :: MOTIVATION Real world objects often exist in various, similar variants Attributes

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

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

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH Data Types Primitive data types (2015F) Lecture2: Java Basics Bohyung Han CSE, POSTECH bhhan@postech.ac.kr Type Bits Minimum Value Maximum Value byte 8 128 127 short 16 32768 32767 int 32 2,147,483,648

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

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

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

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

Inheritance Inheritance 3/3/2014. We have already seen. Object Oriented Programming: Inheritance (Chapter 9) Abstractions Object Oriented Programming: Inheritance (Chapter 9) Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington,

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming

More information

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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

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

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

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

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

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

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and

More information

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

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

Lecture 4: Extending Classes. Concept

Lecture 4: Extending Classes. Concept Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and

More information

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

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

OBJECT 1 ORIENTED PROGRAMMING

OBJECT 1 ORIENTED PROGRAMMING OBJET ORIENTED PROGRAMMING hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Objectives You will learn: Features/facilities of creating a class in Java. Defining class and its members. Scope and lifetime.

More information

Unit 4 - Inheritance, Packages & Interfaces

Unit 4 - Inheritance, Packages & Interfaces Inheritance Inheritance is the process, by which class can acquire the properties and methods of its parent class. The mechanism of deriving a new child class from an old parent class is called inheritance.

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

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

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information