Overloading There is another aspect to polymorphism Overloading

  • Slides: 25
Download presentation
Overloading There is another aspect to polymorphism: Overloading is not overriding. In Turkish: Overridding:

Overloading There is another aspect to polymorphism: 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

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 v. 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 v. 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 Overload. Demo { void test ( ) { System. out.

//Demonstrate method overloading. class Overload. Demo { 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 [ ] ) { Overload. Demo ob= new Overload. Demo ( ) double result; int i =88; //call 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: JBUILDER 8JDK 1. 4binjavaw -classpath "C:

The program generates the following output • C: JBUILDER 8JDK 1. 4binjavaw -classpath "C: WINDOWSjbprojectoverloadingclasses; C: JBUILDER 8JDK 1. 4JR Elibrt. jar; C: . . . . . : JBUILDER 8JDK 1. 4JREclasses; C: JBUILDER 8jdk 1. 4libtools. jar" overloading. Overload No Parameters a: 10 a and b: 10 20 double a: 123. 4 Insidetest(dbl) a: 88 Result of ob. test (123. 4): 15227. 56000001 Inside test(dbl) a: 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.

Automatic Type Conversion § The second version of Overload. Demo does not define test(int).

Automatic Type Conversion § The second version of Overload. Demo does not define test(int). § When test() is called with an integer inside Overload, no matching method is found. v. 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) v. 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

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 v. 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 v. We can use the name sqr to create methods that return the square of an integer and square root of a floating point value. v. These two operations are fundamentally different v. 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

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() v. This method is overloaded by Java’s Math class to handle all numeric types. v. Java determines which version of abs() to call based upon the type of argument. v. The name abs represents the general action which is being performed

Overloading Constructors class Box { double width; //Box () constructor requires three parameters. double

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 overload. Cons { public static void main (String args [ ] ) {

class overload. Cons { public static void main (String args [ ] ) { //create boxes using various constructors Box mybox 1 = new Box (10, 20, 15); Box mybox 2 = new Box (); Box mycube = new Box (7); double vol; //get volume of boxes vol =mybox 1. volume(); System. out. println (“Volume of mybox 1 is ” +vol); vol = mybox 2. volume(); System. out. println (“Volume of mybox 2 is ” +vol); vol =mycube. volume(); System. out. println (“Volume of mycube is ” +vol); } } The program generates the following output C: JBUILDER 8JDK 1. 4binjavaw -classpath "C: WINDOWSjbprojectOverload. Consclasses; C: JBUILDER 8JDK 1. 4JRElibrt. jar; C: JBUILDER 8JDK 1. 4JRElibi 18 n. jar; C: : JBUILDER 8JDK 1. 4JREclasses; C: …………. . JBUILDER 8jdk 1. 4libtools. jar" overloadcons. overload. Cons Volume of mybox 1 is 3000. 0 Volume of mybox 2 is -1. 0 Volume of mycube is 343. 0 § As we can see, the proper overloaded constructor is called based upon the parameters specified when new is executed

class overload. Cons { public static void main (String args [ ] ) {

class overload. Cons { public static void main (String args [ ] ) { //create boxes using various constructors Box mybox 1 = new Box (10, 20, 15); Box mybox 2 = new Box (); Box mycube = new Box (7); double vol; //get volume of boxes vol =mybox 1. volume(); System. out. println (“Volume of mybox 1 is ” +vol); vol = mybox 2. volume(); System. out. println (“Volume of mybox 2 is ” +vol); vol =mycube. volume(); System. out. println (“Volume of mycube is ” +vol); } } The program generates the following output C: JBUILDER 8JDK 1. 4binjavaw -classpath "C: WINDOWSjbprojectOverload. Consclasses; C: JBUILDER 8JDK 1. 4JRElibrt. jar; C: JBUILDER 8JDK 1. 4JRElibi 18 n. jar; C: : JBUILDER 8JDK 1. 4JREclasses; C: …………. . JBUILDER 8jdk 1. 4libtools. jar" overloadcons. overload. Cons Volume of mybox 1 is 3000. 0 Volume of mybox 2 is -1. 0 Volume of mycube is 343. 0 § 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 v.

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

package chp 7; // Parent is superclass of Child // it just defines a

package chp 7; // Parent is superclass of Child // it just defines a string and an access method, get. S() public class Parent { String s = "I am Darth Vader (Parent). "; String get. S() { return s; } //demonstrates overridding get. S() 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 get. S() { // the "super"

class String s; // overrides Parent's method String get. S() { // 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. get. S()); } } 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

§ 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

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

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; v. The object created by the expression new Vector(). v. It has a run-time type of Vector; v. Expressions of the form "new X(. . . )" will always return an instance of X. § There are three variables: vec, list, and obj. v. They all refer to the same object, but each has a different compiletime type ( Vector, List, and Object, respectively).

§ The compiler will allow calls like vec. last. Element(), list. clear(), and obj.

§ The compiler will allow calls like vec. last. Element(), list. clear(), and obj. to. String(), v. Because those are all methods associated with the compile-time types for each of those variables. v. 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. last. Element(), v. Because those methods are not declared by the compile-time types associated with those variables, v 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

io package as Java’s basic I/O system

§ I/O is performed by streams v. A stream is an abstraction that either

§ I/O is performed by streams v. 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 v. Although text -based programs are excellent as teaching examples, Java’s support for console I/O is limited , and textbased console I/O is not very important to Java programming

Streams § Streams are the "fundamental element" of the java. io package § The

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

Reading data § An input stream is typically opened for you automatically v when

Reading data § An input stream is typically opened for you automatically v when it is retrieved from the corresponding data source object or v 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. File. Reader object's constructor as follows: java. io. File. Reader file. Reader = new java. io. File. Reader("/home/me/myfile. txt");

Reading Console Input § Console input is accomplished by reading from System. in §

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 Buffered. Reader (Reader input. Reader) v input. Reader is a stream that is linked to the instance of Buffered. Reader that is being created v Reader is an abstract class ü One of its concrete classes is Input. Stream. Reader, which converts bytes to character. ü To obtain an Input. Stream. Reader object that is linked to System, in , we use the following constructor Input. Stream. Reader(Input. Stream input Stream) Because System. in refers to an object type Input. Stream, it can be used for input. Stream.

Putting all together, the following line of code creates a Bufferedreader that is connected

Putting all together, the following line of code creates a Bufferedreader that is connected to the keyboard Buffered. Reader br= new Buffered. Reader (new Input. Stream. Reader (System. in)); After this statement executes, bt is a character based stream that is linked to the console through System. in v 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 v 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 Buffered. Reader To read a string

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

package untitled 28; import java. io. *; public class BRRead. Lines { public static

package untitled 28; import java. io. *; public class BRRead. Lines { public static void main ( String args[]) throws IOException { //create a Buffered. Reader using System. in Buffered. Reader br= new Buffered. Reader (new Input. Stream. Reader (System. in)); String str; System. out. println ("Enter lines of text. "); System. out. println ("Enter stop' to quit. "); do { str=br. read. Line(); System. out. println (str); } while (!str. equals("stop")); } }