Lab 6
Lab 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.
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.
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:
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);
}
}
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.
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);
}
}
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));
}
}
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;
}
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);
}
}
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);
}
}
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);
}
}
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.
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;
}
}
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());
}
}
public Auto( )
{
model = "unknown";
}
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().