0% found this document useful (0 votes)
16 views

Lab 6

Uploaded by

golatosami09
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lab 6

Uploaded by

golatosami09
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

LECTURE NOTES AND LAB HANDOUTS

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

Topic Covered:
OOP principles, Encapsulation, Inheritance, Polymorphism, Method Overloading, Constructor Overloading,
Passing and Returning Objects and access specifier

OOP PRINCIPLES

ENCAPSULATION
Encapsulation is all about wrapping variables and methods in one single unit. Encapsulation is also known as data
hiding. When you design your class you may (and you should) make your variables hidden from other classes and
provide methods to manipulate the data instead. To achieve encapsulation in Java:
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.

INHERITANCE

Inheritance is the OOP ability that allows Java classes to be derived from other classes. It transfers the
characteristics of a class to other classes that are derived from it. The parent class is called a superclass and the
derivatives are called subclasses. Subclasses inherit fields and methods from their superclasses.

Course Instructor: Nazish Basir Page: 1/14


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

POLYMORPHISM

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability
of a message to be displayed in more than one form. Polymorphism is considered as one of the important
features of Object Oriented Programming. Polymorphism allows us to perform a single action in different ways. In
other words, polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, So it means many forms. In Java polymorphism is mainly divided
into two types:
 Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
 Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function
call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding.

Course Instructor: Nazish Basir Page: 2/14


Institute of Information and Communication Technology, University of Sindh.
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)

Course Instructor: Nazish Basir Page: 3/14


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

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);
}
}

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.

Course Instructor: Nazish Basir Page: 4/14


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

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)
}
}

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

Course Instructor: Nazish Basir Page: 5/14


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

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);
}
}

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.

Course Instructor: Nazish Basir Page: 6/14


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

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;
}

// 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

Course Instructor: Nazish Basir Page: 7/14


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

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: 8/14


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: 9/14


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.

Course Instructor: Nazish Basir Page: 10/14


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

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;
}
}

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());
}
}

PROGRAM 10: 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: 11/14


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; }
}

Course Instructor: Nazish Basir Page: 12/14


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

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( );

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 );
}
}

Course Instructor: Nazish Basir Page: 13/14


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

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: 14/14


Institute of Information and Communication Technology, University of Sindh.

You might also like