Lab Manual 04

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Object Orienting Programming

(Java)

Lab Manual No 04

Dated:
31-Jan-2024
Semester:
2024

Lab Instructor: SHEHARYAR KHAN Page 1


Lab Objective:
In the lecture, we described inheritance features of Object Oriented Programming. We will define
the rules of defining subclasses of programmer-defined classes in this lab. Explanation of how
object-oriented programming allows classes to inherit commonly used state and behavior from
other classes are also provided.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object.

The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship

Why use inheritance in java

13 For Code Reusability.

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

In the terminology of Java, a class which is inherited is called parent or super class and the new class is
called child or subclass.

Lab Instructor: SHEHARYAR KHAN Page 2

43 | P a g e
Example # 01:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){ Programmer
p=new Programmer(); System.out.println("Programmer
salary is:"+p.salary); System.out.println("Bonus of
Programmer is:"+p.bonus);
}}

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

Lab Instructor: SHEHARYAR KHAN Page 3


44 | P a g e
Lab Instructor: SHEHARYAR KHAN Page 4
45 | P a g e
Single Inheritance Example Multilevel Inheritance Example

File: TestInheritance.java File: TestInheritance2.java

class Animal{ class Animal{


void eat(){System.out.println("eating...");} void eat(){System.out.println("eating...");}
} }
class Dog extends Animal{ class Dog extends Animal{
void bark(){System.out.println("barking...");} void bark(){System.out.println("barking...");}
} }
class TestInheritance{ class BabyDog extends Dog{
public static void main(String args[]){ void weep(){System.out.println("weeping...");}
Dog d=new Dog(); }
d.bark(); class TestInheritance2{
d.eat(); public static void main(String args[]){
}} BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Hierarchical Inheritance Example


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error }}

Lab Instructor: SHEHARYAR KHAN Page 5

46 | P a g e
Super Keyword: The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.

4 It is used to differentiate the members of superclass from the members of subclass, if they
have same names.

5 It is used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.

super.variable
super.method();

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.In the given
program, you have two classes namely Sub_class and Super_class, both have a method named display()
with different implementations, and a variable named num with different values. We are invoking
display() method of both classes and printing the value of the variable num of both classes. Here you can
observe that we have used super keyword to differentiate the members of superclass from subclass.

Lab Instructor: SHEHARYAR KHAN Page 6

47 | P a g e
class Super_class {
int num = 20;

3 display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}public class Sub_class extends Super_class {
int num = 10;

D display method of sub


class public void display() {

System.out.println("This is the display method of subclass"); }


public void my_method() {
// Instantiating subclass

6. Invoking the display() method of sub class


sub.display();

Invoking the display() method of


superclass super.display();
printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();}}

Lab Instructor: SHEHARYAR KHAN Page


48 | P a g e
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the default
constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you
need to use the super keyword as shown below.

super(values);

Sample Code
The program given in this section demonstrates how to use the super keyword to invoke the
parametrized constructor of the superclass. This program contains a superclass and a subclass,
where the superclass contains a parameterized constructor which accepts a string value, and we
used the super keyword to invoke the parameterized constructor of the superclass
Example:
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}public static void main(String argd[]) {
Subclass s = new Subclass(24);
s.getAge();}}

Instanceof Operator:
In this example we will show how to use the operator instanceof in Java.This operator is a Type
Comparison Operator and can be used when we want to check if an object is an instance of a specific
class, an instance of a subclass, or an instance of a class that implements a particular interface.
The instanceof operator compares an object to a specified type and returns true if the type of object
and the specified type are the same.

Lab Instructor: SHEHARYAR KHAN Page 8


49 | P a g e
Example :
public class InstanceofExample {

public static void main(String[] args) {


Vehicle vehicle = new Vehicle();
Car car = new Car();
MotorCycle moto = new MotorCycle();

// Those will evaluate to true


System.out.println("vehicle instanceof Vehicle: "
5. (vehicle instanceof Vehicle));
System.out.println("car instanceof Vehicle: "
6. (car instanceof Vehicle));
System.out.println("car instanceof Car: " + (car instanceof Car));

System.out.println("moto instanceof Vehicle: "


+ (moto instanceof Vehicle));
System.out.println("moto instanceof MotorCycle: "
+ (moto instanceof MotorCycle));

// those will evaluate to false

+ (vehicle instanceof Car));


// those will evaluate to false, as the object car is null
car = null;
System.out.println("(car=null) instanceof Vehicle: "
+ (car instanceof Vehicle));
System.out.println("(car=null) instanceof Car: "
+ (car instanceof Car));
}}
class Vehicle {
}
class Car extends Vehicle {
}
class MotorCycle extends Vehicle {
}

Lab Tasks:
Using inheritance create a class Vehicle as super class. Then create motorcycle, car, truck that
inherits the basic functionalities of a vehicle from the super class. Then create the user class in
which user can use any of the vehicles.

Lab Instructor: SHEHARYAR KHAN Page 9


50 | P a g e
Write a java program that includes the class interfaces, class definitions, and code that will test
your classes. Write a main() function along with other functions/procedures, as described below:
a) You shall implement classes that support the following
relationships: A Computer has a central processing unit (CPU).
A PC is a type of Computer.

b) These class relationships are shown in the following diagram.

c) The CPU class is described as follows:


One attribute: clockSpeed – a double value representing the clock speed of the
CPU object. Note: clock speed of a modern computer may be something like
2.5GHz, so a value you could use for testing purposes is 2.5. Two constructors:

A default constructor.
A constructor that initializes the attribute, where cs is the
clockSpeed.
Two methods:
getClockSpeed() – return the clockSpeed value associated
with the CPU object.
setClockSpeed(cs) – change the clockSpeed value associated
with the CPU object, where cs is the new value.

d) The Computer class is described as


follows: One attribute:
processor – a CPU object.
Two constructors:
A default constructor.
A constructor that initializes the attribute, where cpu is
a CPU object.
Two methods:

Lab Instructor: SHEHARYAR KHAN Page 10

51 | P a g e
getCPU() – return the CPU object associated with the Computer
object
setCPU(c) – change the CPU object associated with the
Computer object, where c is the new CPU object.

e) The PC class is described as


follows: One attribute:
operatingSystem – a string value representing the name of the
operating system used on the PC. This value may be something
like “Microsoft Windows XP”, “Linux”, or “Mac OS X”.
Two constructors:
A default constructor.
A constructor that initializes the attributes in the PC and
Computer classes, where cpu is the CPU object and os is the
operatingSystem name.
One method:
print() – display to console output all of the information
associated with this PC object. That is, display the
operatingSystem value, the Computer object information, and
the CPU object information. IMPORTANT: The Computer and CPU
classes do NOT have print() methods. Do NOT add print()
methods to these two classes. Instead, you must use the
appropriate accessor (get) method to obtain each value to be
displayed.

f) The code associated with your main() function should test your three class
definitions. It is important that this code use each constructor defined in each class.

Develop a program that helps the user to draw basic geometrical shapes using Turtles. The
program specification is as follow.

a) Develop a class named JPoint which stores x and y coordinates of stored points with
corresponding getters & setters.
b) Develop an abstract Shape class that contains following members.

turtle: Used to store associated instance with shape


perimeter : Used to store perimeter of shape
area : Used to store area of shape.
It has following abstract methods:
abstract public void draw( )
To draw shape.
abstract public double getPerimeter( )
To get perimeter of shape.

Lab Instructor: SHEHARYAR KHAN Page 11


52 | P a g e
abstract public double getArea()
To get area of shape.

b) Develop a class named Quadrilateral which extends Shape class. It


has following member
int f, g, h, i
Used to Store four points of Quadrilateral

It should have all the corresponding constructors and methods for


valid operation of quadrilateral.

d) Develop a Triangle class which extends Shape class. It


has following members
int a , b , c
Used to store side lengths of Triangle

It should have all the corresponding constructors and methods for


valid operation of a Triangle.

e) Develop an Ellipse class which extends Shape class It


has following members
int cx,cy
Used to Store center point of Ellipse
int Rx,Ry
Used to store lengths of major and minor axes of Ellipse

It should have all the corresponding constructors and methods for


valid operation of an Ellipse.

Test your program by creating one object of each type and calculate the areas
and perimeters.

Develop a program that contains two classes. The specification of both classes is as follow:

a) Data Class

Data class has following members


protected String data
This field stores any type of user data

Data class has following member functions


One argument constructor which takes String object to initialize data.
public void setData(String d)
To set data.
public String getData()

Lab Instructor: SHEHARYAR KHAN Page 12


53 | P a g e
To get data.

b) EncryptedData Class
This class extends the Data class.

This class has following data members


protected String encryptedarray[]
Used to encrypt data.
protected boolean encrypted
To show whether data is encrypted or not.

Data class has following member functions


One argument constructor which takes String argument to initialize superclass
Data
public void encrypt( )
This function encrypts the data.
public void decrypt( )
This function decrypts the already encrypted data.
public String storeData()
This function returns a combination of String which represents EncryptedData
object and stores it in a data file.
public void loadData(String data )
This function loads data from a valid data file.

Encryption Technique :
This is an encryption technique which is a combination of two steps. These steps are as follow:

Step 1: Change the state of each and every bit of lower byte of character, reverse the order of bytes in
character and toggle alternative bits of new lower byte.
Step 2: Create an array of Strings. Length of Array is equal to ceil of square root of length of stored data.
Any String in array can store maximum characters equal to length of array. Store data column
wise is array as first character of data goes to first character of first array , second goes to first
character of second array and so on until first columns are finished then start filling second
columns of all arrays until data and array both are finished. If there are some character fields
in arrays remained but data is exhausted then fill the remaining ones with ‘*’. You can store
data row wise back to data field to store encrypted data.

Suppose data field is “ABCDEFGHIJ”


After first step suppose encrypted data is “KLMNOPQRST”

Then string arrays would be filled like this.

First K O S *
String

Lab Instructor: SHEHARYAR KHAN Page 13


54 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Second L P T *
String
Third M Q * *
String
Fourth N R * *
String

Data will be created again as "KOS*LPT*MQ”


Test your classes by creating two EncryptedData classes. First encrypts data and second uses that to
decrypt data and display actual data. Use storeData( ) and loadData( ) functions to pass data between two
classes. Don’t overload a constructor or a function to copy objects.

Lab Tasks:
ComputerGrades.java file and sample class text file is provided with the manual. Perform the
following tasks after running the given program.
How would you modify the ComputeGrades sample program if the formula for computing
the course grade were different for freshman, sophomore, junior, and senior
undergraduate students?
In the ComputeGrades sample program, we set the default size of the roster array to 25.
Modify the program so the size of the array will be increased if the input file contains
more than 25 students. You need to add a method that expands the array, say by 50
percent.
Modify the ComputeGrades sample program by using a list (ArrayList or LinkedList)
instead of an array.

Lab Instructor: SHEHARYAR KHAN Page 14

55 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Lab Instructor: SHEHARYAR KHAN Page 15

56 | P a g e

You might also like