Overloading There is another aspect to polymorphism: Overloading Overloading is not overriding. In Turkish: Overridding: eskisini (geçersiz kılmak) Overloading:

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
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.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
ITEC200 – Week03 Inheritance and Class Hierarchies.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
04/07/041 Intro to JAVA By: Riyaz Malbari. 04/07/042 History of JAVA  Came into existence at Sun Microsystems, Inc. in  Was initially called “
Io package as Java’s basic I/O system continue’d.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
The Java Programming Language
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: 1) state – name, color, breed, sits?, barks?, wages.
Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University 24/2/2014 Ebtsam Abdelhakam 1.
M1G Introduction to Programming 2 5. Completing the program.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
Methods and Classes. Method Overloading Two or more methods within the same class that share the same name but different parameters class OverloadDemo.
BY:- TOPS Technologies
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
OOP Features Object Oriented Programming Main issues in software engineering – –maintainability, reusability, portability, security, integrity, user.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Objectives You should be able to describe: Interactive Keyboard Input
Java Primer 1: Types, Classes and Operators
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Modern Programming Tools And Techniques-I Inheritance
Constructor Overloading
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Java Programming Language
Java – Inheritance.
I/O and Applet from Chapter 12
Exception Handling Contents
Presentation transcript:

Overloading There is another aspect to polymorphism: Overloading Overloading is not overriding. In Turkish: Overridding: eskisini (geçersiz kılmak) Overloading: Aşırı yüklemek

Overloading Methods  In Java it is possible to define two or more methods within the same class that share the same name, as long as the parameter declarations are different  When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading  Method overloading is one of the ways that Java implements polymorphism  When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actual call  While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method  When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call

//Demonstrate method overloading. class OverloadDemo { void test ( ) { System.out.println ("No Parameters"); } //Overload test for one integer parameter void test (int a) { System.out.println ("a: “ + a); } //Overload test for two integer parameters. void test ( int a, int b) { System.out.println ( "a and b: " +a + “ " + b); } //Overload test for a double parameter. double test (double a) { void test ( double a) { System.out.println ("double a: " + a); System.out.println (“Inside test(dbl) a: " +a); return a*a; } } class Overload { public static void main (String args [ ] ) { OverloadDemo ob= new OverloadDemo ( ) double result; int i =88; //call all variables of test () ob.test(); ob.test(10); ob.test (i) // this will invoke test (dbl) ob.test(10,20); ob.test (123.45); //this will invoke test (dbl) result = ob.test(123.4); System.out.println ("Result of ob.test (123.4): " + result ); } }

The program generates the following output C:\JBUILDER8\JDK1.4\bin\javaw -classpath "C:\WINDOWS\jbproject\overloading\classes;C:\JBUILDER8\JDK1.4\JR E\lib\rt.jar;C:\ :\JBUILDER8\JDK1.4\JRE\classes;C: \JBUILDER8\jdk1.4\lib\tools.jar" overloading.Overload No Parameters a: 10 a and b: double a: Inside test (dbl) a:88 Result of ob.test (123.4):  As we can see, test() is overloaded four times.  The fourth version of test() also return a value is of no consequence relative to overloading, since return types do not play a role in overloaded resolution  When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method’s parameter.  This match need not always be exact.  In some automatic Java’s automatic type conversions can play a role in overloaded resolution. Inside test (dbl) a:88 Inside test(dbl) a:123.4

Automatic Type Conversion  The second version of OverloadDemo does not define test(int).  When test() is called with an integer inside Overload, no matching method is found.  Java can automatically convert an integer into a double, and this conversion can be used to resolve the call  After test(int) is not found, Java elevates i to double and then calls test(double)  If test(int) had been defined it would have been called.  Java will employ its automatic type conversion only no exact match is found.

The Superiority of Method Overloading  “One interface, multiple methods” paradigm is implemented by Java  If a language do not support method overloading, each method must be a unique name  However, it is frequently required to implement the same method for different types of data  There is no rule stating that overloaded methods must relate to one another  We can use the name sqr to create methods that return the square of an integer and square root of a floating point value.  These two operations are fundamentally different  Applying method overloading in this manner defeats its original purpose  In practice, we should only overload closely related operations

The Advantage of Overloading According to C  For example, absolute value function in C has three versions, abs( ) returns absolute value of a integer, labs( ) returns absolute value of a long integer, and fabs( ) returns absolute value of a floating-point value.  Since C does not support overloading, each function has its own name, even though all three functions do essentially the same thing.  Java’s standard class library includes an absolute value method, called abs()  This method is overloaded by Java’s Math class to handle all numeric types.  Java determines which version of abs() to call based upon the type of argument.  The name abs represents the general action which is being performed  Through the application of polymorphism, several names have been reduced to one.

Overloading Constructors class Box { double width; //Box () constructor requires three parameters. double height; // This means all declarations of Box objects must double depth; // pass three argumants to the Box() constructor Box (double w, double h, double d) { width = w; height =h; depth =d; } //constructor used when no dimensions specified Box ( ) { // use -1 to indicate width = -1; // an uninitialized height= -1; // box depth = -1 } //constructor used when cube is created Box (double len) { width = height = depth = len; } //compute and return volume double volume ( ) { return width*height*depth; }

class overloadCons { public static void main (String args [ ] ) { //create boxes using various constructors Box mybox1 = new Box (10,20,15); Box mybox2 = new Box (); Box mycube = new Box (7); double vol; //get volume of boxes vol =mybox1.volume(); System.out.println (“Volume of mybox1 is ” +vol); vol = mybox2.volume(); System.out.println (“Volume of mybox2 is ” +vol); vol =mycube.volume(); System.out.println (“Volume of mycube is ” +vol); } The program generates the following output C:\JBUILDER8\JDK1.4\bin\javaw -classpath "C:\WINDOWS\jbproject\OverloadCons\classes;C:\JBUILDER8\JDK1.4\JRE\lib\rt.jar; C:\JBUILDER8\JDK1.4\JRE\lib\i18n.jar;C:\:\JBUILDER8\JDK1.4\JRE\classes;C:\ ………….. JBUILDER8\jdk1.4\lib\tools.jar" overloadcons.overloadCons Volume of mybox1 is Volume of mybox2 is -1.0 Volume of mycube is  As we can see, the proper overloaded constructor is called based upon the parameters specified when new is executed

class overloadCons { public static void main (String args [ ] ) { //create boxes using various constructors Box mybox1 = new Box (10,20,15); Box mybox2 = new Box (); Box mycube = new Box (7); double vol; //get volume of boxes vol =mybox1.volume(); System.out.println (“Volume of mybox1 is ” +vol); vol = mybox2.volume(); System.out.println (“Volume of mybox2 is ” +vol); vol =mycube.volume(); System.out.println (“Volume of mycube is ” +vol); } The program generates the following output C:\JBUILDER8\JDK1.4\bin\javaw -classpath "C:\WINDOWS\jbproject\OverloadCons\classes;C:\JBUILDER8\JDK1.4\JRE\lib\rt.jar; C:\JBUILDER8\JDK1.4\JRE\lib\i18n.jar;C:\:\JBUILDER8\JDK1.4\JRE\classes;C:\ ………….. JBUILDER8\jdk1.4\lib\tools.jar" overloadcons.overloadCons Volume of mybox1 is Volume of mybox2 is -1.0 Volume of mycube is  As we can see, the proper overloaded constructor is called based upon the parameters specified when new is executed

Here is an example of method overriding  This example defines two classes  Parent and  Child.  The Parent class defines a simple string s, and it defines one method for retrieving that string, getS().  The Child class also defines a getS() method,  Therefore overriding the Parent class's getS().  They have the same name, but they do different things.  The main difference between an overloaded method and an overridden method is that overriding does not allow you to change the return type.

package chp7; // Parent is superclass of Child // it just defines a string and an access method, getS() public class Parent { String s = "I am Darth Vader (Parent). "; String getS() { return s; } //demonstrates overridding getS() method of Parent // "extends" means that Child inherits from the Parent class public class Child extends Parent { // this value is part of the Child

class String s; // overrides Parent's method String getS() { // the "super" keyword calls the parent of current class. // i.e. "super" refers to the value after the "extends" keyword s = super.s + " I am Luke (child). "; return s; } public static void main(String [] args) { // make a new baby Child luke = new Child(); // call the Child's overriding method System.out.println (luke.getS()); } Here is the output of running Child: I am Darth Vader (Parent). I am Luke (child).

 Overloading occurs in the compiler at compile time.  The compiler chooses which one you mean by finding the corresponding argument type to what you called for.  By contrast, overriding occurs at runtime.  It happens when one class extends another, and  the subclass has a method with the same signature as a method of the superclass.

Question: Explain the difference between compile-time type and run-time type  Variables and other Java source code expressions have a compile-time type, which the compiler uses to determine legality of certain expressions (such as field accesses or method calls).  Objects that are created during the execution of a Java program have a run-time type, which the Java virtual machine uses to determine what method implementations should be called and to check the legality of casts. According to type checking: "compile-time type" means "apparent type" and "run-time type" means "actual type”

Here is an example to help distinguish between compile-time types and run-time types: import java.util.Vector; import java.util.List;... Vector vec = new Vector(); List list = vec; Object obj = list;...  There is only one instance of an object;  The object created by the expression new Vector().  It has a run-time type of Vector;  Expressions of the form "new X(...)" will always return an instance of X.  There are three variables: vec, list, and obj.  They all refer to the same object, but each has a different compile-time type ( Vector, List, and Object, respectively).VectorListObject

 The compiler will allow calls like vec.lastElement(), list.clear(), and obj.toString(), vec.lastElement()list.clear() obj.toString()  Because those are all methods associated with the compile-time types for each of those variables.  The compiler will also statically ensure that the Vector class actually implements all of those methods  Because the Vector class subclasses Object and implements List.  The compiler will not allow calls like obj.clear() or list.lastElement(),  Because those methods are not declared by the compile-time types associated with those variables,  therefore are not guaranteed to be implemented by every object that the variables might point to.

io package as Java’s basic I/O system

 I/O is performed by streams  A stream is an abstraction that either produces or consumes information  Java implements streams within class hierarchies defined in the java.io package  Since most real applications of Java are not text-based, console programs, none of I/O methods have been used significantly except print() and println()  We generally generate graphically oriented applets using AWT for the interaction  Although text -based programs are excellent as teaching examples, Java’s support for console I/O is limited, and text- based console I/O is not very important to Java programming

Streams  Streams are the "fundamental element" of the java.io package  The simplest streams are the abstract classes InputStream and OutputStream  We cannot use them directly  They define i/o in terms of bytes

Reading data  An input stream is typically opened for you automatically  when it is retrieved from the corresponding data source object or  when you construct one of the reader objects.  For example, to open the input stream for a file, we pass the name of the file into a java.io.FileReader object's constructor as follows: java.io.FileReader fileReader = new java.io.FileReader("/home/me/myfile.txt");

Reading Console Input  Console input is accomplished by reading from System.in  To obtain a character based stream that is attached to console, we wrap System.in in a Buffered Reader object to create a character stream BufferedReader (Reader inputReader)  inputReader is a stream that is linked to the instance of BufferedReader that is being created  Reader is an abstract class One of its concrete classes is InputStreamReader, which converts bytes to character. To obtain an InputStreamReader object that is linked to System,in,we use the following constructor InputStreamReader(InputStream input Stream) Because System.in refers to an object type InputStream, it can be used for inputStream.

Putting all together, the following line of code creates a Bufferedreader that is connected to the keyboard BufferedReader br= new BufferedReader (new InputStreamReader (System.in)); After this statement executes, bt is a character based stream that is linked to the console through System.in  To read a character from a Buffered Reader, we use read(). The version of read() that we will be using is: int read() throws IO Exception  Each time read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of stream is encountered.

Following program reads a string from console using BufferedReader To read a string from keyboard, we use the version readLine() that is the member of BufferedReader class. String readLine() throws IO Exception As we can see, it returns a String object.

package untitled28; import java.io.*; public class BRReadLines { public static void main ( String args[]) throws IOException { //create a BufferedReader using System.in BufferedReader br= new BufferedReader (new InputStreamReader (System.in)); String str; System.out.println ("Enter lines of text."); System.out.println ("Enter stop' to quit."); do { str=br.readLine(); System.out.println (str); } while (!str.equals("stop")); } }