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 MethodsIn 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 polymorphismWhen 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 callWhile 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\JRE\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: 10 20 double a: 123.4 Inside test (dbl) a:88 Result of ob.test (123.4): 15227.560000000001
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:88Inside 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 nameHowever, 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 anotherWe 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 Constructorsclass 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 specifiedBox ( ) { // use -1 to indicatewidth = -1; // an uninitializedheight= -1; // boxdepth = -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 3000.0 Volume of mybox2 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 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 3000.0 Volume of mybox2 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 classesParent 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).
The compiler will allow calls like vec.lastElement(), list.clear(), and 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 streamsA 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 createdReader 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")); } }