EKT472: Object Oriented Programming. Overloading and Overriding Method

Similar documents
Object Orientation, Overloading and Overriding, Constructors, and Return Types

CSA 1019 Imperative and OO Programming

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

Inheritance and Polymorphism

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

CS-202 Introduction to Object Oriented Programming

Inheritance (continued) Inheritance

CS1150 Principles of Computer Science Objects and Classes

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Java Object Oriented Design. CSC207 Fall 2014

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

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

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

Chapter 5 Object-Oriented Programming

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Practice for Chapter 11

Chapter 11 Inheritance and Polymorphism

What is Inheritance?

Inheritance, Polymorphism, and Interfaces

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Polymorphism and Inheritance

Class, Variable, Constructor, Object, Method Questions

Inheritance and Polymorphism

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

Chapter 5. Inheritance

More Relationships Between Classes

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 14 Abstract Classes and Interfaces

Inheritance and Polymorphism

Inheritance -- Introduction

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

1 Shyam sir JAVA Notes

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

Making New instances of Classes

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

First IS-A Relationship: Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Inheritance (Outsource: )

Programming in C# Inheritance and Polymorphism

8. Polymorphism and Inheritance

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

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

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

ITI Introduction to Computing II

25. Generic Programming

CS Programming I: Inheritance

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

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

ITI Introduction to Computing II

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

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

Computer Science II (20073) Week 1: Review and Inheritance

Java Fundamentals (II)

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Rules and syntax for inheritance. The boring stuff

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Data Structures (list, dictionary, tuples, sets, strings)

Introductory Programming Inheritance, sections

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

Lecture 18 CSE11 Fall 2013 Inheritance

Java Magistère BFA

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming: Based on slides from Skrien Chapter 2

Example: Count of Points

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

301AA - Advanced Programming [AP-2017]

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Introduction to Inheritance

C++ Important Questions with Answers

AP CS Unit 6: Inheritance Notes

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

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

What are the characteristics of Object Oriented programming language?

Exercise: Singleton 1

Classes and Inheritance Extending Classes, Chapter 5.2

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

COP 3330 Final Exam Review

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCE3193: Programming Paradigms

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Instance Members and Static Members

Inheritance. Chapter 7. Chapter 7 1

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CST242 Object-Oriented Programming Page 1

Transcription:

EKT472: Object Oriented Programming Overloading and Overriding Method

2 Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name When a method is overridden, the new method definition given in the derived class has the exact same number and types of parameters as in the base class When a method in a derived class has a different signature from the method in the base class, that is overloading Note that when the derived class overloads the original method, it still inherits the original method from the base class as well

3 Overriding vs. Overloading public class Test { public static void main(string[] args) { A a = new A(); a.p(10); class B { public void p(int i) { class A extends B { // This method overrides the method in B public void p(int i) { System.out.println(i); public class Test { public static void main(string[] args) { A a = new A(); a.p(10); class B { public void p(int i) { class A extends B { // This method overloads the method in B public void p(double i) { System.out.println(i); The method p(int i) in class A overloads the The method p(int i) in class A overrides the same method defines in class B. same method defines in class B.

4 Overloading Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). Overloading a method often means you're being a little nicer to those who call your methods, because your code takes on the burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking your method.

5 Overloading rules Overloaded methods MUST change the argument list. Overloaded methods CAN change the return type. Overloaded methods CAN change the access modifier. Overloaded methods CAN declare new or broader checked exceptions. A method can be overloaded in the same class or in a subclass.

6 Legal Overloads public void changesize(int size, String name, float pattern) { The following methods are legal overloads of the changesize() method: public void changesize(int size, String name) { public int changesize(int size, float pattern) { public void changesize(float pattern, String name){

7 Invoking Overloaded Methods When a method is invoked, more than one method of the same name might exist for the object type you're invoking a method on. For example, the Adder class might have two methods with the same name but with different argument lists, which means the method is overloaded.

8 Class Adder public class Adder { public int addthem(int x, int y) { return x + y; // Overload the addthem method to add doubles instead of ints public double addthem(double x, double y) { return x + y;

9 Class TestAdder public class TestAdder { public static void main (String [] args) { Adder a = new Adder(); int b = 27; int c = 3; // Which addthem is invoked? int result = a.addthem(b,c); double doubleresult = a.addthem(22.5,9.3); System.out.println (result); System.out.println (doubleresult);

10 The first call to a.addthem(b, c) passes two ints to the method, so the first version of addthem() the overloaded version that takes two int arguments is called. The second call to a.addthem(22.5, 9.3) passes two doubles to the method, so the second version of addthem() the overloaded version that takes two double arguments is called.

11 Invoking overloaded methods that take object references class Animal { class Horse extends Animal { public class UseAnimals { public void dostuff(animal a) { System.out.println("In the Animal version"); public void dostuff(horse h) { System.out.println("In the Horse version");

12 Invoking overloaded methods that take object references public class TestUseAnimals2 { public static void main (String [] args) { UseAnimals ua = new UseAnimals(); Animal animalobj = new Animal(); Horse horseobj = new Horse(); Animal animalreftohorse = new Horse(); ua.dostuff(animalobj); ua.dostuff(horseobj); ua.dostuff(animalreftohorse);

13 Lets say, one version takes an Animal and one takes a Horse (subclass of Animal). If you pass a Horse object in the method invocation, you'll invoke the overloaded version that takes a Horse. If you use an Animal reference to a Horse object, the compiler knows only about the Animal, so it chooses the overloaded version of the method that takes an Animal. Even though the actual object at runtime is a Horse and not an Animal, the choice of which overloaded method to call (in other words, the signature of the method) is NOT dynamically decided at runtime. To summarize, which overridden version of the method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time.

14

15

16

Overriding Method

18 The Object Class Every class in Java is descended from the java.lang.object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. public class Circle {... Equivalent public class Circle extends Object {...

19 Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override the methods of the superclass

20 The tostring() method in Object The tostring() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Circle circ = new Circle(); System.out.println(circ.toString()); The code displays something like Circle@82ba41. This message is not very helpful or informative. Usually you should override the tostring method so that it returns a digestible string representation of the object.

21 Example 1: Object + tostring(): String By default, all Java classes are subclasses of the Object class (the most general class in Java s hierarchy). Student # name : String + Student() + Student(s:String) + getname(): String One public method that is defined in the Object class is the tostring()method.

22 Example 1: public class Student { protected String name; public Student () { public Student (String s) { name = s; public String getname() { return name; public class TestStudent1 { public static void main( String args[]){ Student stu = new Student("Ana"); System.out.println (stu.tostring());

23 Example 1: output Student@82ba41 Name of the object Address of the object The default implementation of tostring() Returns the name of the object s class and the address where the object is stored in the memory.

24 Example 2: Overriding an Inherited Method Object + tostring(): String tostring()method is redefined in subclasses of Object class. Student # name : String + Student() + Student(s:String) + getname(): String + tostring():string Overriding tostring()in a Subclass provides a customized string representation of the Object in that subclass.

25 Example 2 public class Student { protected String name; public Student () { public Student (String s) { name = s; public String getname() { return name; public String tostring() { return "My name is " + name + " and I am a Student.";

26 Example 2 public class TestStudent2 { public static void main( String args[]){ Student stu = new Student("Ana"); System.out.println (stu.tostring()); Output: My name is Ana and I am a Student.

27 Overriding Methods in the Superclass Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method (unless, the method is marked final). The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); class Horse extends Animal { public void eat() { System.out.println("Horse eating hay, oats, " + "and horse treats"); public void buck() { System.out.println ("This is how I jump");

28 Overriding Methods in the Superclass public class TestAnimals { public static void main (String [] args) { Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() The Animal class creator might have decided that for the purposes of polymorphism, all Animal subtypes should have an eat() method defined in a unique, specific way. Polymorphically, when someone has an Animal reference that refers not to an Animal instance, but to an Animal subclass instance, the caller should be able to invoke eat() on the Animal reference, but the actual runtime object (say, a Horse instance) will run its own specific eat() method.

29 Overriding Methods in the Superclass public class TestAnimal2 { public static void main (String [] args) { Animal c = new Horse(); //Animal ref, but a Horse object c.buck(); The TestAnimal2 class uses an Animal reference to invoke a method on a Horse object. Remember, the compiler will allow only methods in class Animal to be invoked when using a reference to an Animal. Can't invoke buck(); because Animal class doesn't have that method.

30 Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the tostring method defined in GeometricObject */ public String tostring() { return super.tostring() + "\nradius is " + radius;

31 Invoking a Superclass Version of an Overridden Method The keyword super can also be used to reference a method in the superclass. public class Animal2 { public void eat() { public void printyourself() { // Useful printing code goes here class Horse extends Animal2 { public void printyourself() { // Take advantage of Animal code, then add some more super.printyourself(); // Invoke the superclass // (Animal) code // Then do Horse-specific // print work here

32 Dynamic Binding A method call is bound to the correct implementation of the method at runtime by the Java Virtual Machine (JVM). When JVM encounters a method call, it uses information about the class hierarchy to bind the method call to the correct implementation of that method. Java s dynamic-binding mechanism, which is also called late binding, or runtime binding, leads to what is known as polymorphism.

33 NOTE An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class.

34 A private method cannot be overridden public class TestAnimals3 { public static void main (String [] args) { Horse h = new Horse(); h.eat(); class Animal { private void eat() { System.out.println("Generic Animal Eating Generically"); class Horse extends Animal { Method eat() in the superclass can t be inherited, because it is private. Therefore, method eat() cannot be overridden.

35 NOTE If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.

36 A private method cannot be overridden public class TestAnimals2 { public static void main (String [] args) { Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); class Horse extends Animal { private void eat() { // whoa! - it's private! System.out.println("Horse eating hay, oats, " + "and horse treats");