Sunteți pe pagina 1din 11

LECTURE NOTES AND LAB HANDOUTS

OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

METHOD OVERLOADING
Method Overloading is a feature that allows a class to have more than one method having the same name, if their
argument lists are different. Argument list it means the parameters that a method has: For example the argument
list of a method add(int a, int b) having two parameters is different from the argument list of the method add(int
a, int b, int c) having three parameters. In order to overload a method, the argument lists of the methods must
differ in either of these:

1. Number of parameters. For example:


add(int, int)
add(int, int, int)
2. Data type of parameters. For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters. For example:
add(int, float)
add(float, int)

PROGRAM 1: Demonstrate method overloading. To run Program save this file “Overload.java”

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) {
System.out.println("double a: " + a);
return a*a;
}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

Course Instructor: Nazish Basir Page: 1/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

INVALID CASE OF METHOD OVERLOADING:


If two methods have same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw compilation error.
int add(int, int)
float add(int, int)

AUTOMATIC TYPE CONVERSION IN OVERLOADING


When an overloaded method is called, Java looks for a match between the arguments used to call the method and
the method’s parameters. However, this match need not always be exact. In some cases, Java’s automatic type
conversions can play a role in overload resolution.

PROGRAM 2: Automatic type conversions apply to overloading. Save this file “Overload.java”

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// 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
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}

Course Instructor: Nazish Basir Page: 2/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

CONSTRUCTOR OVERLOADING
Constructor overloading is a concept of having more than one constructor with different parameters list, in such a
way so that each constructor performs a different task.

PROGRAM 3: Constructor Overloading

class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// 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 the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

Course Instructor: Nazish Basir Page: 3/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

PASSING AND RETURNING OBJECTS IN JAVA


Although Java is strictly pass by value, the precise effect differs between whether a primitive type or a reference
type is passed.
When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the
situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this
interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference. Basically, a parameter cannot
be changed by the function, but the function can ask the parameter to change itself via calling some method within
it.
 While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this
reference to a method, the parameter that receives it will refer to the same object as that referred to by
the argument.
 This effectively means that objects act as if they are passed to methods by use of call-by-reference.
 Changes to the object inside the method do reflect in the object used as an argument.

PROGRAM 4: Passing objects to methods.

class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}

PROGRAM 5: Here, Box allows one object to initialize another.

class Box {
double width;
double height;
double depth;
// Notice this constructor. It takes an object of type Box.
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}

Course Instructor: Nazish Basir Page: 4/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of mybox1
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}

Course Instructor: Nazish Basir Page: 5/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

PROGRAM 6: Primitive types are passed by value.

class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}

PROGRAM 7: Objects are passed by reference.

class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}

Course Instructor: Nazish Basir Page: 6/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

PROGRAM 8: Returning an object from methods.

class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);

ACCESS SPECIFIER
For each class and for each member of a class, we need to provide an access modifier that specifies where the class
or member can be used.

Access Modifier Class or member can be referenced by ….


Public Methods of the same class as well as methods of the other class
Private Methods of the same class only
Protected Methods in the same class, as well as methods in sub-classes and methods in same package
No modifier Methods in the same package only

Typically access modifier for a class will be public and if class defined with public modifier than it must be stored
with same file name.

PROGRAM 9: This program demonstrates the difference between public and private.

class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}

Course Instructor: Nazish Basir Page: 7/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}

STATIC CLASS MEMBERS


There will be times when you will want to define a class member that will be used independently of any object of
that class. Normally, a class member must be accessed only in conjunction with an object of its class. However, it
is possible to create a member that can be used by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword static. When a member is declared static, it can be accessed
before any objects of its class are created, and without reference to any object. You can declare both methods and
variables to be static.
Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no
copy of a static variable is made. Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described
in the next chapter.)
If you need to do computation in order to initialize your static variables, you can declare astatic block that gets
executed exactly once, when the class is first loaded.

ACCESS RESTRICTION FOR STATIC AND NON-STATIC METHODS


Static method Non-static method
Access instance variables no Yes
Access static class variables yes Yes
Call static class methods yes Yes
Call non-static instance methods no Yes
Use the reference this no Yes

Course Instructor: Nazish Basir Page: 8/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

PROGRAM 10: Demonstrate static variables, methods, and blocks.


class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}

PROGRAM 11: Demonstrate static variables and method are accessed through their class name.

class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}

PROGRAM 12: Demonstrate an Auto class for creating cars

public class Auto


{
// instance variables
private String model; //model of auto
private int milesDriven; //number of miles driven
private double gallonsOfGas; //number of gallons of gas

// Default constructor: initializes model to "unknown";


// milesDriven is auto-initialized to 0 and gallonsOfGas to 0.0
public Auto( )
{
model = "unknown";
}

Course Instructor: Nazish Basir Page: 9/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

// Overloaded constructor: allows client to set beginning values for


// model, milesDriven, and gallonsOfGas.

public Auto( String startModel,


int startMilesDriven,
double startGallonsOfGas )
{
model = startModel;

// validate startMiles parameter


if ( startMilesDriven >= 0 )
milesDriven = startMilesDriven;
else
{
System.err.println( "Miles driven is negative." );
System.err.println( "Value set to 0." );
}

// validate startGallonsOfGas parameter


if ( startGallonsOfGas >= 0.0 )
gallonsOfGas = startGallonsOfGas;
else
{
System.err.println( "Gallons of gas is negative" );
System.err.println( "Value set to 0.0." );
}
}

// Accessor method: returns current value of model


public String getModel( )
{ return model; }

// Accessor method: returns current value of milesDriven


public int getMilesDriven( )
{ return milesDriven; }

// Accessor method: returns current value of gallonsOfGas


public double getGallonsOfGas( )
{ return gallonsOfGas; }
}

public class AutoClient


{
public static void main( String [] args )
{
Auto sedan = new Auto( );
String sedanModel = sedan.getModel( );
int sedanMiles = sedan.getMilesDriven( );
double sedanGallons = sedan.getGallonsOfGas( );

Course Instructor: Nazish Basir Page: 10/11


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 6

System.out.println( "sedan: model is " + sedanModel


+ "\n miles driven is " + sedanMiles
+ "\n gallons of gas is " + sedanGallons );

Auto suv = new Auto( "Trailblazer", 7000, 437.5 );


String suvModel = suv.getModel( );
int suvMiles = suv.getMilesDriven( );
double suvGallons = suv.getGallonsOfGas( );
System.out.println( "suv: model is " + suvModel
+ "\n miles driven is " + suvMiles
+ "\n gallons of gas is " + suvGallons );
}
}

EXERCISE 1:
Write a Java class Clock for dealing with the day time represented by hours, minutes, and seconds. Your class must
have the following features:
 Three instance variables for the hours (range 0 - 23), minutes (range 0 - 59), and seconds (range 0 - 59).
 Three constructors:
1. default (with no parameters passed; is should initialize the represented time to 12:0:0)
2. a constructor with three parameters: hours, minutes, and seconds.
3. a constructor with one parameter: the value of time in seconds since midnight (it should be converted into the
time value in hours, minutes, and seconds)
 Instance methods:
1. a set-method method setClock() with one parameter seconds since midnight (to be converted into the time
value in hours, minutes, and seconds as above).
2. get-methods getHours(), getMinutes(), getSeconds() with no parameters that return the corresponding values.
3. set-methods setHours(), setMinutes(), setSeconds() with one parameter each that set up the corresponding
instance variables.
4. method tick() with no parameters that increments the time stored in a Clock object by one second.
5. method addClock() accepting an object of type Clock as a parameter. The method should add the time
represented by the parameter class to the time represented in the current class.
6. Add an instance method toString() with no parameters to your class. toString() must return a String
representation of the Clock object in the form "(hh:mm:ss)", for example "(03:02:34)".
7. Add an instance method tickDown() which decrements the time stored in a Clock object by one second.
8. Add an instance method subtractClock() that takes one Clock parameter and returns the difference between
the time represented in the current Clock object and the one represented by the Clock parameter. Difference
of time should be returned as an clock object.
Write a separate class ClockDemo with a main() method. The program should:
 instantiate a Clock object firstClock using one integer seconds since midnight obtained from the keyboard.
 tick the clock ten times by applying its tick() method and print out the time after each tick.
 Extend your code by appending to it instructions instantiating a Clock object secondClock by using three
integers (hours, minutes, seconds) read from the keyboard.
 Then tick the clock ten times, printing the time after each tick.
 Add the secondClock time in firstClock by calling method addClock.
 Print both clock objects calling toString method
Create a reference thirdClock that should reference to object of difference of firstClock and secondClock by calling
the method subtractClock().

Course Instructor: Nazish Basir Page: 11/11


Institute of Information and Communication Technology, University of Sindh.

S-ar putea să vă placă și