You are on page 1of 80

LAB 07 Access Modifiers, this keyword & static keyword

Task 1: Write another class in which you write main method and access the
attributes of following class.

SOLUTION :

class Test

int a = 2;

public int b =4;

private int c;

void setc(int i )

c=i;

int getc()

return c;

public class Task1044{

public static void main(String [] args)

Test t = new Test();

t.setc(6);

System.out.println("a : " + t.a);


System.out.println("b : " + t.b);

System.out.println("c : " + t.getc());

OUTPUT :

a:2

b:4

c:6

Task 2: Write constructor of the above class (Test.java) and declare it private.
Now try to create object of the above class in another class.

SOLUTION :

class Test

int a ;

public int b ;

private int c;

private Test ( int a , int b )

this.a=a;

this.b=b;

void setc(int i )

c=i;

}
int getc()

return c;

public class Task2044{

public static void main(String [] args)

Test t = new Test(2,4);

t.setc(6);

System.out.println("a : " + t.a);

System.out.println("b : " + t.b);

System.out.println("c : " + t.getc());

OUTPUT :

Main.java:25: error: Test(int,int) has private access in Test

Test t = new Test(2,4);

1 error

Task 3: Run following code. Is it written correctly ?

package p1;

class X

{
protected int i = 1221;

void methodOfX()

System.out.println(i);

public class MainClass

public static void main( String[] args )

X x = new X();

System.out.println(x.i);

x.methodOfX();

OUTPUT :

1221

1221

Yes this code is written correctly .

Task 4: this: to refer current class instance variable. Write a class in which names
of class data members are same as constructor arguments.

SOLUTION :

class Student

int rollno;
String name;

float fee ;

Student (int rollno , String name , float fee )

this.rollno = rollno;

this.name=name;

this.fee = fee;

public void display()

System.out.println( "Roll no : " + rollno) ;

System.out.println( "Name : " + name) ;

System.out.println( "Fee : " + fee) ;

public class Task3044{

public static void main(String[] args)

Student s = new Student ( 44 , "Syeda Rutab Aziz" , 52000.0f );

s.display() ;
}

OUTPUT :

Roll no : 44

Name : Syeda Rutab Aziz

Fee : 52000.0

Task 5: this: to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor. In other words, it is used for constructor
chaining.

Reuse of constructor from constructor

1. Create a class names as Student

2. create a constructor of this class which takes rollno, course and name as
parameter and assign them to variables of rollno, course and name
respectively

3. Create another constructor which takes arguments: rollno, course, name


and fee. Assign fee to fee variable and call first constructor to assign other
three arguments.

4. Call class using three and four parameters.

SOLUTION :
class Student

int rollNo;

String course;

String name;

double fee;

Student(int rollNo, String course, String name)


{

this.rollNo = rollNo;

this.course = course;

this.name = name;

Student(int rollNo, String course, String name, double fee)

this(rollNo, course, name);

this.fee = fee;

public void displayInfo() {

System.out.println("Roll No: " + rollNo);

System.out.println("Name: " + name);

System.out.println("Course: " + course);

System.out.println("Fee: " + fee);

System.out.println();

public static void main(String[] args)

Student s1 = new Student(1, "Computer Science", "Ali");

s1.displayInfo();

Student s2 = new Student(2, "Electrical Engineering", "Ahmed", 5000.00);

s2.displayInfo();

}
OUTPUT :

Roll No: 1

Name: Ali

Course: Computer Science

Fee: 0.0

Roll No: 2

Name: Ahmed

Course: Electrical Engineering

Fee: 5000.0

Task 6:

A. Calculate cube using a method

⦁ Create a class named as calculate

⦁ Write a method, count in which returns cube of the given variable.

⦁ Write main method which calls the count method

SOLUTION :

public class Calculate {

// Non-static method to calculate the cube of a given variable

public int count(int number) {

return number * number * number;

// Main method

public static void main(String[] args) {

// Create an instance of Calculate

Calculate calculator = new Calculate();


// Example usage: calculate the cube of 5 using the non-static method

int result = calculator.count(5);

// Display the result

System.out.println("The cube of 5 is: " + result);

B. Calculate cube using static method

Now change count method to static by adding static keyword

Call count method from main to calculate cube

SOLUTION :

public class Calculate {

// Method to calculate the cube of a given variable

public static int count(int number) {

return number * number * number;

// Main method

public static void main(String[] args) {

// Example usage: calculate the cube of 5

int result = count(5);

// Display the result

System.out.println("The cube of 5 is: " + result);

OUTPUT :
The cube of 5 is: 125

Question 1: Can the constructor of a class be declared private? What will be


consequences?

Yes, the constructor of a class can be declared private. If the constructor is private, it means
that instances of the class can only be created within the class itself. This can be useful in
certain design patterns, such as the Singleton pattern, where you want to ensure that only
one instance of the class can exist.

Question 2: What is the difference between private and protected data


members of a class?

The main difference between private and protected data members of a class lies in their
accessibility:

Private Data Members:


Accessible only within the class in which they are declared.
Not accessible in derived classes (subclasses).
Protected Data Members:
Accessible within the class in which they are declared.
Accessible in derived classes (subclasses).

Question 3: What is ‘default’ access modifier?

The 'default' access modifier in Java is also known as package-private or package-local. It


means that the member (class, method, or field) is accessible within the same package. If no
access modifier is specified, it defaults to package-private.

Question 4: Write the content of the constructor whose parameter names are
same as the member variables name.

class ClassConstructorOperations

public static void main(String s[])

Student student = new Student( "Lavanya", 501, 95.6 );

System.out.println(student.rollNumber + " is the roll number of " +


student.name + " and she secured " + student.percentage + " % in SSC" );

}
class Student

String name;

int rollNumber;

double percentage;

//Write a constructor here to initialize the parameters.

if the parameter names in the constructor are the same as the member variables'
names, you can use the this keyword to distinguish between the constructor
parameters and the class members.

class ClassConstructorOperations

public static void main(String s[])

Student student = new Student( "Lavanya", 501, 95.6 );

System.out.println(student.rollNumber + " is the roll number of " +


student.name + " and she secured " + student.percentage + " % in SSC" );

class Student

String name;

int rollNumber;

double percentage;

//Write a constructor here to initialize the parameters.

Student ( String name , int rollNumber , double percentage )


{

this.name=name;

this.rollNumber=rollNumber;

this.percentage = percentage;

Question 5: What will be the output of the program?

public class Karbon {

static int i = 5;

public static void main(String[] args) {

Karbon test = null;

System.out.print("i = " + test.i + ", ");

System.out.print("i = " + Karbon.i);

}}

The provided code will result in a NullPointerException because the test object is
assigned a value of null, and attempting to access i on a null reference will result in a
runtime exception.

Exception in thread "main" java.lang.NullPointerException

at Karbon.main(Karbon.java:6)

LAB 08 Finalize, Nested & Inner Classes

TASK 1: See Output of the following Program

class A {

int i = 50;

@Overrideprotected void finalize() throws Throwable {

System.out.println("From Finalize Method"); }


}

public class Test

public static void main(String[] args)

//Creating two instances of class A

A a1 = new A();

A a2 = new A();

//Assigning a2 to a1

a1 = a2;

//Now both a1 and a2 will be pointing to same object

//An object earlier referred by a1 will become

//abandoned

System.gc();System.out.println("done");

The output of the provided program is not guaranteed to be consistent, as it depends


on the behavior of the garbage collector, which is managed by the Java Virtual
Machine (JVM). The System.gc() method is a hint to the JVM to run the garbage
collector, but it does not guarantee immediate execution.

TASK 2: Value of final variable cannot be changed once declared. Run the following
code and check output.

class Bike9{

final int speedlimit=90;//final variable

void run(){

speedlimit=400;

}
public static void main(String args[])

Bike9obj=new Bike9(); obj.run();

}//end of class

The code has a compilation error and won't run successfully. The issue is with the
attempt to modify the value of a final variable speedlimit within the run method. Once a
final variable is assigned a value, it cannot be changed.

TASK 3: Try to initialize value of final variable in a constructorTASK 4: Do not initialize


final variable on declaration and try to initialize it anywhere other than constructor.

class Bike9 {

final int speedlimit; // final variable

// Constructor to initialize the final variable

public Bike9() {

speedlimit = 90;

// Attempting to change the value of final variable will result in a compilation error

void run() {

// Compilation error: cannot assign a value to final variable 'speedlimit'

// speedlimit = 400;

public static void main(String args[]) {

Bike9 obj = new Bike9();

// Accessing the final variable after initialization


System.out.println("Speed Limit: " + obj.speedlimit);

// obj.run(); // Uncommenting this line would cause a compilation error

TASK 4: Declare final variable as static and try to initialize its value in a
method. Then create a static block and initialize the static final variable
value.

class Bike9 {

// Static final variable

static final int speedLimit;

// Static block to initialize the static final variable

static {

speedLimit = 90;

// You can perform additional initialization tasks in the static block if needed

// Method attempting to initialize the static final variable (not allowed)

static void initializeSpeedLimit() {

// Compilation error: cannot assign a value to final variable 'speedLimit'

// speedLimit = 100;

public static void main(String args[]) {

// Accessing the static final variable

System.out.println("Speed Limit: " + Bike9.speedLimit);

// Calling the method attempting to initialize the static final variable


(commented out to avoid compilation error)
// Bike9.initializeSpeedLimit();

TASK 5: Run the following code and try to understand its working

// Demonstrate an inner class.

class Outer {

int outer_x = 100;

void test() {

Inner inner = new Inner();

inner.display();

// this is an inner class

class Inner {

void display() { System.out.println("display: outer_x = " + outer_x); }

class InnerClassDemo {

public static void main(String args[]) {

Outer outer = new Outer();

outer.test();

}}

TASK 6: Declare a local variable in inner class and try to display it in outer
class.

SOLUTION :
In Java, you cannot directly declare a local variable in an inner class and then display
it in the outer class, as the scope of a local variable is limited to the method or block
where it is declared. However, you can achieve a similar effect by defining an instance
variable in the inner class and then accessing that instance variable from the outer
class. Here's an example:

public class OuterClass_044 {

private int outerVariable = 5; // instance variable in the outer class

public void outerMethod() {

// Define an inner class

class InnerClass {

private int innerVariable = 10; // instance variable in the inner class

public void displayVariables() {

// Access both outer and inner variables

System.out.println("Outer Variable: " + outerVariable);

System.out.println("Inner Variable: " + innerVariable);

// Create an instance of the inner class

InnerClass innerObj = new InnerClass();

// Call the method in the inner class to display variables

innerObj.displayVariables();

public static void main(String[] args) {


// Create an instance of the outer class

OuterClass outerObj = new OuterClass();

// Call the outer method

outerObj.outerMethod();

TASK 7: Declare a private variable in outer class and try to display it in


inner class.

SOLUTION :

public class OuterClass_044 {

private int privateVariable = 42; // private instance variable in the outer


class

// Inner class definition

class InnerClass {

public void displayOuterVariable() {

// Access the private variable of the outer class

System.out.println("Private Variable in OuterClass: " + privateVariable);

public static void main(String[] args) {

// Create an instance of the outer class


OuterClass outerObj = new OuterClass();

// Create an instance of the inner class

InnerClass innerObj = outerObj.new InnerClass();

// Call the method in the inner class to display the outer variable

innerObj.displayOuterVariable();

TASK 8: Try to declare inner class within a method of outer


class.
public class OuterClass {

private int outerVariable = 42; // instance variable in the outer class

public void outerMethod() {

// Declare a local inner class within the outer method

class LocalInnerClass {

public void displayOuterVariable() {

// Access the outer variable from the outer method

System.out.println("Outer Variable in OuterClass: " + outerVariable);

// Create an instance of the local inner class


LocalInnerClass localInnerObj = new LocalInnerClass();

// Call the method in the local inner class to display the outer variable

localInnerObj.displayOuterVariable();

public static void main(String[] args) {

// Create an instance of the outer class

OuterClass outerObj = new OuterClass();

// Call the outer method

outerObj.outerMethod();

TASK 9: Run and Learn from following code:

public class Outer {

static class Nested_Demo {

public void my_method() {

System.out.println("This is my nested class");

}}

public static void main(String args[])

Outer.Nested_Demo nested = new Outer.Nested_Demo();


nested.my_method();

}}
Question 1: What is the purpose of garbage collector in java?
The purpose of the garbage collector in Java is to automatically manage the memory
used by your program by reclaiming memory occupied by objects that are no longer in
use. In Java, memory for objects is allocated on the heap, and over time, objects may
become unreachable or unused. Without a garbage collector, it would be the
responsibility of the developer to manually free up memory, leading to potential
memory leaks and inefficiencies.

Question 2: If the final variable is initialized at the time of declaration


then can it be re-initialized in constructor?

No, if a final variable is initialized at the time of declaration, it cannot be re-initialized


in the constructor or anywhere else in the code. Once a final variable is assigned a
value, that value cannot be changed throughout the lifetime of the variable. This is
one of the characteristics of a final variable in Java.

Question 3: Can final variable be initialized somewhere other then


constructor?
Yes, a final variable in Java can be initialized at the time of declaration or within an
instance initializer block. An instance initializer block is a block of code within a class
that is executed when an instance of the class is created. The final variable must be
assigned a value either at the time of declaration, within an instance initializer block,
or within the constructor. Once a final variable is assigned a value, it cannot be
changed.

Question 4: What will be the output of the program?

class Output

final static short i = 2;

public static int j = 0;

public static void main(String [] args)

for (int k = 0; k < 3; k++)

switch (k)
{

case i: System.out.print(" 0 ");

case i-1: System.out.print(" 1 ");

case i-2: System.out.print(" 2 ");

OUTPUT :
01212

Question 5: What will be the output of the following program?

public class Final

final int assign = 30;

public static void main(String[] args)

final int result = 20;

final int assign;

Final f = new Final();

assign = 20;

System.out.println(assign);

System.out.println(f.assign);

System.out.println(f.process(result));

}
int process(int a)

return a + 5;

OUTPUT :
20

30

25

LAB 09 Inheritance in Java

TASK 1: Run and understand the following code

// A simple example of inheritance.

// Create a superclass.

clas

s A {int i, j;

void showij() {

System.out.println("i and j: " + i + " " + j);

// Create a subclass by extending class A.

class B extends A {

int k;

void showk() {
System.out.println("k: " + k);

void sum() {

System.out.println("i+j+k: " + (i+j+k));

class SimpleInheritance {

public static void main(String args []) {

A superOb = new A();

B subOb = new B();

// The superclass may be used by itself.

superOb.i = 10;

superOb.j = 20;

System.out.println("Contents of superOb: ");

superOb.showij();

System.out.println();

/* The subclass has access to all public members of

its superclass. */

subOb.i = 7;

subOb.j = 8;

subOb.k = 9;
System.out.println("Contents of subOb: ");

subOb.showij();

subOb.showk();

System.out.println();

System.out.println("Sum of i, j and k in subOb:");

subOb.sum();

TASK 2: Create a class A which has two data members one is public and other
is private. Create another class B which extends class A. Try to display
values of both data members of class A in class B.

SOLUTION :

class A {

// Public data member

public String publicMember = "I am public!";

// Private data member

private String privateMember = "I am private!";

// Getter method for private member

public String getPrivateMember() {

return privateMember;

class B extends A {
// Method to display values of both data members of class A

void displayValues() {

// Accessing public member of class A

System.out.println("Public member of class A: " + publicMember);

// Accessing private member of class A using the getter method

System.out.println("Private member of class A: " + getPrivateMember());

public class Main_044 {

public static void main(String[] args) {

// Creating an object of class B

B objB = new B();

// Displaying values of both data members in class B

objB.displayValues();

TASK 3: Continuing with TASK 2. Display some statements in the


constructors of both class A and class B and now try to create object of
class B to observe which constructor was called first.

class A {

// Public data member

public String publicMember = "I am public!";


// Private data member

private String privateMember = "I am private!";

// Constructor for class A

public A() {

System.out.println("Constructor of class A called.");

// Getter method for private member

public String getPrivateMember() {

return privateMember;

class B extends A {

// Constructor for class B

public B() {

// Calling the constructor of the superclass (class A)

super();

System.out.println("Constructor of class B called.");

// Method to display values of both data members of class A

void displayValues() {

// Accessing public member of class A

System.out.println("Public member of class A: " + publicMember);


// Accessing private member of class A using the getter method

System.out.println("Private member of class A: " + getPrivateMember());

public class Main_044 {

public static void main(String[] args) {

// Creating an object of class B

B objB = new B();

// Displaying values of both data members in class B

objB.displayValues();

TASK 4: Imagine a publishing company that markets both book and audiocassette
versions of its works. Create a class publication that stores the title (a string) and
price (type float) of a publication. From this class derive two classes: book, which
adds a page count (type int), and tape, which adds a playing time in minutes (type
float). Each of these three classes should have a getdata() function to get its data
from the user at the keyboard, and a putdata() function to display its data.

Write a main() program to test the book and tape classes by creating instances of
them, asking the user to fill in data with getdata(), and then displaying the data
with putdata().

SOLUTION :

import java.util.Scanner;

class Publication {

// Data members
protected String title;

protected float price;

// Function to get data from the user

public void getData() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter title: ");

title = scanner.nextLine();

System.out.print("Enter price: ");

price = scanner.nextFloat();

// Function to display data

public void putData() {

System.out.println("Title: " + title);

System.out.println("Price: $" + price);

class Book extends Publication {

// Additional data member for Book

private int pageCount;

// Overriding the getData() function to include page count

@Override

public void getData() {


super.getData();

Scanner scanner = new Scanner(System.in);

System.out.print("Enter page count: ");

pageCount = scanner.nextInt();

// Overriding the putData() function to display page count

@Override

public void putData() {

super.putData();

System.out.println("Page Count: " + pageCount);

class Tape extends Publication {

// Additional data member for Tape

private float playingTime;

// Overriding the getData() function to include playing time

@Override

public void getData() {

super.getData();

Scanner scanner = new Scanner(System.in);

System.out.print("Enter playing time (in minutes): ");

playingTime = scanner.nextFloat();

}
// Overriding the putData() function to display playing time

@Override

public void putData() {

super.putData();

System.out.println("Playing Time: " + playingTime + " minutes");

public class Main {

public static void main(String[] args) {

// Testing the Book class

Book book = new Book();

System.out.println("Enter data for the book:");

book.getData();

System.out.println("\nBook Information:");

book.putData();

// Testing the Tape class

Tape tape = new Tape();

System.out.println("\nEnter data for the tape:");

tape.getData();

System.out.println("\nTape Information:");

tape.putData();

}
}

TASK 5: Drive a class called RegularEmployee and HourlyEmploee from the


Employee class. RegularEmployee should add a type double data item
called basicSalary. HourlyEmploee should add a type double data item
called hourlyRate and another double data type item called noOfHours to
calculate salary for hours worked. In both classes add appropriate functions
to take their information from user and display it as well.

SOLUTION:

import java.util.Scanner;

class Employee {

// Common data members for all types of employees

protected String name;

protected int employeeId;

// Function to get common data from the user

public void getData() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter employee name: ");

name = scanner.nextLine();

System.out.print("Enter employee ID: ");

employeeId = scanner.nextInt();

// Function to display common data

public void putData() {

System.out.println("Employee Name: " + name);


System.out.println("Employee ID: " + employeeId);

class RegularEmployee extends Employee {

// Additional data member for RegularEmployee

private double basicSalary;

// Function to get specific data for RegularEmployee from the user

public void getRegularEmployeeData() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter basic salary: $");

basicSalary = scanner.nextDouble();

// Function to display specific data for RegularEmployee

public void putRegularEmployeeData() {

System.out.println("Basic Salary: $" + basicSalary);

class HourlyEmployee extends Employee {

// Additional data members for HourlyEmployee

private double hourlyRate;

private double noOfHours;


// Function to get specific data for HourlyEmployee from the user

public void getHourlyEmployeeData() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter hourly rate: $");

hourlyRate = scanner.nextDouble();

System.out.print("Enter number of hours worked: ");

noOfHours = scanner.nextDouble();

// Function to display specific data for HourlyEmployee

public void putHourlyEmployeeData() {

System.out.println("Hourly Rate: $" + hourlyRate);

System.out.println("Number of Hours Worked: " + noOfHours);

// Function to calculate and display the salary for hours worked

public void displaySalary() {

double salary = hourlyRate * noOfHours;

System.out.println("Salary for Hours Worked: $" + salary);

public class Main_044 {

public static void main(String[] args) {

// Testing the RegularEmployee class

RegularEmployee regularEmployee = new RegularEmployee();


System.out.println("Enter data for the regular employee:");

regularEmployee.getData();

regularEmployee.getRegularEmployeeData();

System.out.println("\nRegular Employee Information:");

regularEmployee.putData();

regularEmployee.putRegularEmployeeData();

// Testing the HourlyEmployee class

HourlyEmployee hourlyEmployee = new HourlyEmployee();

System.out.println("\nEnter data for the hourly employee:");

hourlyEmployee.getData();

hourlyEmployee.getHourlyEmployeeData();

System.out.println("\nHourly Employee Information:");

hourlyEmployee.putData();

hourlyEmployee.putHourlyEmployeeData();

hourlyEmployee.displaySalary();

LAB 10 Super Keyword and Polymorphism in Java

TASK 1: super keyword is used to refer immediate parent class instance


variable.

We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields. Perform
following steps
Create a class and its sub class both having same data member.

Use super in child class to print the value of parent class variable.

create a test class to implement main method with demo functionality

// Parent class

class ParentClass {

// Common data member for both ParentClass and ChildClass

protected int commonVariable = 10;

// Child class inheriting from ParentClass

class ChildClass extends ParentClass {

// Data member with the same name as in ParentClass

private int commonVariable = 20;

// Method to print the value of commonVariable using super keyword

public void displayCommonVariable() {

// Using super to access the commonVariable from the parent class

System.out.println("Value of commonVariable in ParentClass: " +


super.commonVariable);

System.out.println("Value of commonVariable in ChildClass: " +


this.commonVariable);

// Test class with main method

public class Main {


public static void main(String[] args) {

// Creating an object of ChildClass

ChildClass childObject = new ChildClass();

// Calling the method to display the values

childObject.displayCommonVariable();

TASK 2: super Keyword can be used to invoke parent class method.

The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class. In
other words, it is used if method is overridden. Perform following steps

Create a class animal with a method eat() which prints "eating"

Create subclass of animal class with method bark() which prints "barking"
and method eat() same name as super class but it prints "eating meat"

Write a print() method in subclass which call all the super and sub class
methods.

// Parent class

class Animal {

// Method in the parent class

public void eat() {

System.out.println("Eating");

// Subclass inheriting from Animal

class Dog extends Animal {


// Overridden method in the subclass

@Override

public void eat() {

System.out.println("Eating meat");

// Additional method in the subclass

public void bark() {

System.out.println("Barking");

// Method in the subclass calling both parent and subclass methods

public void print() {

// Calling the eat() method from the parent class using super

super.eat();

// Calling the overridden eat() method in the subclass

eat();

// Calling the bark() method in the subclass

bark();

// Test class with main method

public class Main {


public static void main(String[] args) {

// Creating an object of the Dog class

Dog dog = new Dog();

// Calling the print() method to see the output

dog.print();

TASK 3: super Keyword is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.
Create a scenario in which above use of the super keyword is depicted.

// Parent class

class Animal {

// Parent class constructor

public Animal() {

System.out.println("Constructor of Animal class");

// Method in the parent class

public void eat() {

System.out.println("Eating");

// Subclass inheriting from Animal

class Dog extends Animal {


// Subclass constructor using super to invoke the parent class constructor

public Dog() {

super(); // Invoking the constructor of the parent class

System.out.println("Constructor of Dog class");

// Overridden method in the subclass

@Override

public void eat() {

System.out.println("Eating meat");

// Additional method in the subclass

public void bark() {

System.out.println("Barking");

// Test class with main method

public class Main {

public static void main(String[] args) {

// Creating an object of the Dog class

Dog dog = new Dog();

// Calling the eat() method to see the output

dog.eat();
// Calling the bark() method to see the output

dog.bark();

TASK 4: Run the following code

class student

int rollno;

String name;

student(int r, String n)

rollno = r;

name = n;

void dispdatas()

System.out.println("Rollno = " + rollno);

System.out.println("Name = " + name);

class marks extends student

int total;
marks(int r, String n, int t)

super(r,n); //call super class (student) constructor

total = t;

void dispdatam()

dispdatas(); // call dispdatap of student class

System.out.println("Total = " + total);

class percentage extends marks

int per;

percentage(int r, String n, int t, int p)

super(r,n,t); //call super class(marks) constructor

per = p;

void dispdatap()

dispdatam(); // call dispdatap of marks class


System.out.println("Percentage = " + per);

class Multi_Inhe

public static void main(String args[])

percentage stu = new percentage(102689, "RATHEESH", 350, 70); //call


constructor percentage

stu.dispdatap(); // call dispdatap of percentage class

OUTPUT :

Rollno = 102689

Name = RATHEESH

Total = 350

Percentage = 70

Task 05: Consider a scenario, Bank is a class that provides functionality to


get rate of interest. But, rate of interest varies according to banks. For
example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of
interest.

// Bank class

class Bank {

// Method to get the rate of interest

public double getInterestRate() {

return 0.0; // Default implementation, to be overridden by subclasses


}

// SBI subclass

class SBI extends Bank {

// Overriding the getInterestRate method for SBI

@Override

public double getInterestRate() {

return 8.0; // SBI provides 8% rate of interest

// ICICI subclass

class ICICI extends Bank {

// Overriding the getInterestRate method for ICICI

@Override

public double getInterestRate() {

return 7.0; // ICICI provides 7% rate of interest

// AXIS subclass

class AXIS extends Bank {

// Overriding the getInterestRate method for AXIS

@Override

public double getInterestRate() {


return 9.0; // AXIS provides 9% rate of interest

// Test class with main method

public class Main {

public static void main(String[] args) {

// Creating objects of the subclasses

SBI sbi = new SBI();

ICICI icici = new ICICI();

AXIS axis = new AXIS();

// Displaying the rate of interest for each bank

System.out.println("SBI Interest Rate: " + sbi.getInterestRate() + "%");

System.out.println("ICICI Interest Rate: " + icici.getInterestRate() + "%");

System.out.println("AXIS Interest Rate: " + axis.getInterestRate() + "%");

Task 06: Create Object in following manner:

Bank obj = new SBI();

// Bank class

class Bank {

// Method to get the rate of interest


public double getInterestRate() {

return 0.0; // Default implementation, to be overridden by subclasses

// SBI subclass

class SBI extends Bank {

// Overriding the getInterestRate method for SBI

@Override

public double getInterestRate() {

return 8.0; // SBI provides 8% rate of interest

// Test class with main method

public class Main {

public static void main(String[] args) {

// Creating an object of SBI and assigning it to a reference of Bank

Bank obj = new SBI();

// Calling the getInterestRate method using the reference of Bank

double interestRate = obj.getInterestRate();

// Displaying the interest rate

System.out.println("Interest Rate: " + interestRate + "%");

}
}

LAB 11 Abstraction in Java


Task 1: Implement the following Class diagram.

In this exercise, Shape shall be defined as an abstract class, which contains:

Two protected instance variables color(String) and filled(boolean). The protected


variables can be accessed by its subclasses and classes in the same package. They
are denoted with a '#' sign in the class diagram.

Getter and setter for all the instance variables, and toString().

Two abstract methods getArea() and getPerimeter() (shown in italics in the class
diagram).

The subclasses Circle and Rectangle shall override the abstract methods getArea()
and getPerimeter() and provide the proper implementation. They also override
the toString().

abstract class Shape {

// Protected instance variables

protected String color;

protected boolean filled;

public Shape ( )

System.out.println (“ Shape class Constructor ” );

public Shape(String color, boolean filled) {

this.color = color;

this.filled = filled;

// Getter and setter for color


public String getColor() {

return color;

public void setColor(String color) {

this.color = color;

// Getter and setter for filled

public boolean isFilled() {

return filled;

public void setFilled(boolean filled) {

this.filled = filled;

// Abstract methods

public abstract double getArea();

public abstract double getPerimeter();

// toString method

@Override

public String toString() {

return "Shape[color=" + color + ", filled=" + filled + "]";


}

class Circle extends Shape {

private double radius;

public Circle ( double radius )

{
this.radius=radius;

public Circle(double radius, String color, boolean filled) {

super(color, filled);

this.radius = radius;

// Getter and setter for radius

public double getRadius() {

return radius;

public void setRadius(double radius) {

this.radius = radius;

// Override abstract methods

@Override

public double getArea() {


return Math.PI * radius * radius;

@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

// Override toString method

@Override

public String toString() {

return "Circle[" + super.toString() + ", radius=" + radius + "]";

class Rectangle extends Shape {

private double width;

private double height;

// Constructor

public Rectangle(double width, double height, String color, boolean filled) {

super(color, filled);

this.width = width;

this.height = height;

}
// Getter and setter for width

public double getWidth() {

return width;

public void setWidth(double width) {

this.width = width;

// Getter and setter for height

public double getHeight() {

return height;

public void setHeight(double height) {

this.height = height;

// Override abstract methods

@Override

public double getArea() {

return width * height;

@Override

public double getPerimeter() {


return 2 * (width + height);

// Override toString method

@Override

public String toString() {

return "Rectangle[" + super.toString() + ", width=" + width + ", height=" + height + "]";

public class Main {

public static void main(String[] args) {

// Create a Circle

Circle circle = new Circle(5.0, "Red", true);

// Display Circle information

System.out.println("Circle:");

System.out.println("Color: " + circle.getColor());

System.out.println("Filled: " + circle.isFilled());

System.out.println("Radius: " + circle.getRadius());

System.out.println("Area: " + circle.getArea());

System.out.println("Perimeter: " + circle.getPerimeter());

System.out.println(circle); // Calls the overridden toString method

System.out.println();

// Create a Rectangle

Rectangle rectangle = new Rectangle(4.0, 6.0, "Blue", false);


// Display Rectangle information

System.out.println("Rectangle:");

System.out.println("Color: " + rectangle.getColor());

System.out.println("Filled: " + rectangle.isFilled());

System.out.println("Width: " + rectangle.getWidth());

System.out.println("Height: " + rectangle.getHeight());

System.out.println("Area: " + rectangle.getArea());

System.out.println("Perimeter: " + rectangle.getPerimeter());

System.out.println(rectangle); // Calls the overridden toString method

Task 02: Try to run following code in your main method after implementation of
TASK 1

Shape s1 = new Circle(5.5, "RED", false); // Upcast Circle to Shape

System.out.println(s1); // which version?

System.out.println(s1.getArea()); // which version?

System.out.println(s1.getPerimeter()); // which version?


System.out.println(s1.getColor());

System.out.println(s1.isFilled());

System.out.println(s1.getRadius());

Circle c1 = (Circle)s1; // Downcast back to Circle

System.out.println(c1);

System.out.println(c1.getArea());

System.out.println(c1.getPerimeter());

System.out.println(c1.getColor());

System.out.println(c1.isFilled());

System.out.println(c1.getRadius());

Shape s2 = new Shape();

Shape s3 = new Rectangle(1.0, 2.0, "RED", false); // Upcast

System.out.println(s3);

System.out.println(s3.getArea());

System.out.println(s3.getPerimeter());

System.out.println(s3.getColor());

System.out.println(s3.getLength());

Rectangle r1 = (Rectangle)s3; // downcast

System.out.println(r1);

System.out.println(r1.getArea());

System.out.println(r1.getColor());

System.out.println(r1.getLength());
Shape s4 = new Square(6.6); // Upcast

System.out.println(s4);

System.out.println(s4.getArea());

System.out.println(s4.getColor());

System.out.println(s4.getSide());

// Take note that we downcast Shape s4 to Rectangle,

// which is a superclass of Square, instead of Square

Rectangle r2 = (Rectangle)s4;

System.out.println(r2);

System.out.println(r2.getArea());

System.out.println(r2.getColor());

System.out.println(r2.getSide());

System.out.println(r2.getLength());

// Downcast Rectangle r2 to Square

Square sq1 = (Square)r2;

System.out.println(sq1);

System.out.println(sq1.getArea());

System.out.println(sq1.getColor());

System.out.println(sq1.getSide());

System.out.println(sq1.getLength());

SOLUTION :

abstract class Shape {

// Protected instance variables


protected String color;

protected boolean filled;

public Shape ( )

System.out.println (“ Shape class Constructor ” );

public Shape(String color, boolean filled) {

this.color = color;

this.filled = filled;

// Getter and setter for color

public String getColor() {

return color;

public void setColor(String color) {

this.color = color;

// Getter and setter for filled

public boolean isFilled() {

return filled;

public void setFilled(boolean filled) {


this.filled = filled;

// Abstract methods

public abstract double getArea();

public abstract double getPerimeter();

// toString method

@Override

public String toString() {

return "Shape[color=" + color + ", filled=" + filled + "]";

class Circle extends Shape {

private double radius;

public Circle ( double radius )

{
this.radius=radius;

public Circle(double radius, String color, boolean filled) {

super(color, filled);

this.radius = radius;

}
// Getter and setter for radius

public double getRadius() {

return radius;

public void setRadius(double radius) {

this.radius = radius;

// Override abstract methods

@Override

public double getArea() {

return Math.PI * radius * radius;

@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

// Override toString method

@Override

public String toString() {

return "Circle[" + super.toString() + ", radius=" + radius + "]";

}
class Rectangle extends Shape {

private double width;

private double height;

// Constructor

public Rectangle(double width, double height, String color, boolean filled) {

super(color, filled);

this.width = width;

this.height = height;

// Getter and setter for width

public double getWidth() {

return width;

public void setWidth(double width) {

this.width = width;

// Getter and setter for height

public double getHeight() {

return height;

}
public void setHeight(double height) {

this.height = height;

// Override abstract methods

@Override

public double getArea() {

return width * height;

@Override

public double getPerimeter() {

return 2 * (width + height);

// Override toString method

@Override

public String toString() {

return "Rectangle[" + super.toString() + ", width=" + width + ", height=" + height + "]";

class Square extends Shape {

private double side;

public Square(double side, String color, boolean filled) {

super(color, filled);
this.side = side;

public double getSide() {

return side;

public void setSide(double side) {

this.side = side;

@Override

public double getArea() {

return side * side;

@Override

public double getPerimeter() {

return 4 * side;

@Override

public String toString() {

return "Square[" + super.toString() + ", side=" + side + "]";

}
public class Main {

public static void main(String[] args) {

// Task 1 code...

// Task 2 code

System.out.println("Task 2 Code:");

// Upcast Circle to Shape

Shape s1 = new Circle(5.5, "RED", false);

System.out.println(s1);

System.out.println("Area: " + s1.getArea()); // Calls Circle's getArea method

System.out.println("Perimeter: " + s1.getPerimeter());// Calls Circle's getPerimeter


method

System.out.println("Color: " + s1.getColor());

System.out.println("Filled: " + s1.isFilled());

// Downcast back to Circle

Circle c1 = (Circle) s1;

System.out.println(c1);

System.out.println("Area: " + c1.getArea()); // Calls Circle's getArea method

System.out.println("Perimeter: " + c1.getPerimeter());// Calls Circle's getPerimeter


method

System.out.println("Color: " + c1.getColor());

System.out.println("Filled: " + c1.isFilled());

System.out.println("Radius: " + c1.getRadius());

// Upcast Rectangle to Shape


Shape s3 = new Rectangle(1.0, 2.0, "RED", false);

System.out.println(s3);

System.out.println("Area: " + s3.getArea()); // Calls Rectangle's getArea method

System.out.println("Perimeter: " + s3.getPerimeter());// Calls Rectangle's getPerimeter


method

System.out.println("Color: " + s3.getColor());

// Downcast back to Rectangle

Rectangle r1 = (Rectangle) s3;

System.out.println(r1);

System.out.println("Area: " + r1.getArea()); // Calls Rectangle's getArea method

System.out.println("Color: " + r1.getColor());

// Upcast Square to Shape

Shape s4 = new Square(6.6, "Blue", true);

System.out.println(s4);

System.out.println("Area: " + s4.getArea()); // Calls Square's getArea method

System.out.println("Color: " + s4.getColor());

// Downcast to Rectangle (not Square)

Rectangle r2 = (Rectangle) s4;

System.out.println(r2);

System.out.println("Area: " + r2.getArea()); // Calls Square's getArea method


(dynamic dispatch)

System.out.println("Color: " + r2.getColor());

System.out.println("Perimeter: " + r2.getPerimeter());// Calls Rectangle's getPerimeter


method
// Downcast to Square

Square sq1 = (Square) s4;

System.out.println(sq1);

System.out.println("Area: " + sq1.getArea()); // Calls Square's getArea method

System.out.println("Color: " + sq1.getColor());

System.out.println("Perimeter: " + sq1.getPerimeter());// Calls Square's getPerimeter


method

System.out.println("Side: " + sq1.getSide());

TASK 03: Create one superclass called Employee and two subclasses –
Contractor and FullTimeEmployee. Both subclasses have common
properties to share, like the name of the employee and the amount of
money the person will be paid per hour. There is one major difference
between contractors and full-time employees – the time they work for the
company. Full-time employees work constantly 8 hours per day and the
working time of contractors may vary

class Employee {

private String name;

private double hourlyRate;

public Employee(String name, double hourlyRate) {

this.name = name;

this.hourlyRate = hourlyRate;

public String getName() {


return name;

public double getHourlyRate() {

return hourlyRate;

// Common method for both subclasses to calculate payment

public double calculatePayment(double hoursWorked) {

return hoursWorked * hourlyRate;

class Contractor extends Employee {

private int contractDuration; // Duration of the contract in days

public Contractor(String name, double hourlyRate, int contractDuration) {

super(name, hourlyRate);

this.contractDuration = contractDuration;

public int getContractDuration() {

return contractDuration;

}
class FullTimeEmployee extends Employee {

// Full-time employees work 8 hours per day

private static final int FULL_TIME_HOURS_PER_DAY = 8;

public FullTimeEmployee(String name, double hourlyRate) {

super(name, hourlyRate);

// Override calculatePayment method for full-time employees

@Override

public double calculatePayment(double hoursWorked) {

// Full-time employees work a fixed 8 hours per day

return FULL_TIME_HOURS_PER_DAY * getHourlyRate();

public class Main {

public static void main(String[] args) {

// Create a contractor

Contractor contractor = new Contractor("John Contractor", 25.0, 30);

System.out.println("Contractor:");

System.out.println("Name: " + contractor.getName());

System.out.println("Hourly Rate: $" + contractor.getHourlyRate());

System.out.println("Contract Duration: " + contractor.getContractDuration() + "


days");

System.out.println("Payment: $" + contractor.calculatePayment(40)); //


Assuming 40 hours worked
System.out.println();

// Create a full-time employee

FullTimeEmployee fullTimeEmployee = new FullTimeEmployee("Jane FullTime",


30.0);

System.out.println("Full-Time Employee:");

System.out.println("Name: " + fullTimeEmployee.getName());

System.out.println("Hourly Rate: $" + fullTimeEmployee.getHourlyRate());

System.out.println("Payment: $" + fullTimeEmployee.calculatePayment(40)); //


Assuming 40 hours worked

LAB 12 Encapsulation and Packages in Java


TASK 01: Run the following sample code

/* File name : EncapTest.java */

public class EncapTest {

private String name;

private String idNum;

private int age;

public int getAge() {

return age;

public String getName() {

return name;

public String getIdNum() {


return idNum;

public void setAge( int newAge) {

age = newAge;

public void setName(String newName) {

name = newName;

public void setIdNum( String newId) {

idNum = newId;

Accessing of above class using following class

/* File name : RunEncap.java */

public class RunEncap {

public static void main(String args[]) {

EncapTest encap = new EncapTest();

encap.setName("James");

encap.setAge(20);

encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

OUTPUT :
Name: James Age: 20

Task 02: Create a class Employee with age, name and ssn as private data members.

Write set ad get methods for the private data members. Methods must apply
following conditions:

Name is not null

SSN is between 100 and 999

Age is not a negative number

Age is not 0.

Try to set the values of the Employee class data members using another class and
also display the values of the data members.

class Employee {

private String name;

private int age;

private int ssn;

public String getName() {

return name;

public void setName(String name) {

// Check if name is not null

if (name != null) {

this.name = name;

} else {

System.out.println("Name cannot be null.");

}
public int getAge() {

return age;

public void setAge(int age) {

// Check if age is not a negative number and not 0

if (age > 0) {

this.age = age;

} else {

System.out.println("Invalid age. Age must be a positive number.");

public int getSsn() {

return ssn;

public void setSsn(int ssn) {

// Check if SSN is between 100 and 999

if (ssn >= 100 && ssn <= 999) {

this.ssn = ssn;

} else {

System.out.println("Invalid SSN. SSN must be between 100 and 999.");

}
}

public class EmployeeTest {

public static void main(String[] args) {

// Create an instance of Employee

Employee employee = new Employee();

// Set values using set methods with conditions

employee.setName("John Doe");

employee.setAge(25);

employee.setSsn(123);

// Display employee details

System.out.println("Employee Details:");

System.out.println("Name: " + employee.getName());

System.out.println("Age: " + employee.getAge());

System.out.println("SSN: " + employee.getSsn());

Task 03: Create packages and try to access private, protected, public and
default data members in another package. Also create subclasses a class
outside its package and try to access private, protected, default and public
data members.

Package Structure:

Package company:

Class Employee in package company:


Contains private, protected, default, and public data members.
Package hr:

Class HREmployee in package hr:


Imports company.Employee.
No inheritance from Employee.
Accesses private, protected, default, and public members using an instance of
Employee.

Package main:

Class Main in package main:


Contains the main method to demonstrate the usage of Employee and
HREmployee classes.

1. Employee class in the company package:

package company;

public class Employee {

private String privateField = "Private Field";

protected String protectedField = "Protected Field";

String defaultField = "Default Field";

public String publicField = "Public Field";

2. HREmployee class in the hr package:

package hr;

import company.Employee;

public class HREmployee {

public void accessFields() {

// Create an instance of Employee within the method

Employee employee = new Employee();


// Accessing fields of the Employee class through the local instance

System.out.println("Protected Field: " + employee.protectedField);

System.out.println("Default Field: " + employee.defaultField);

System.out.println("Public Field: " + employee.publicField);

// Uncommenting the line below will result in a compilation error because 'privateField' is
private

// System.out.println("Private Field: " + employee.privateField);

3. Main class in the main package:

package main;

import hr.HREmployee;

public class Main {

public static void main(String[] args) {

// Create an instance of HREmployee

HREmployee hrEmployee = new HREmployee();

// Accessing fields of the Employee class through HREmployee

hrEmployee.accessFields();

LAB 13 Interface in Java


Task 1: Developing a Payable Hierarchy
To build an application that can determine payments for employees and invoices
alike, we first create interface Payable, which contains method
getPaymentAmount that returns a double amount that must be paid for an object
of any class that implements the interface. After declaring interface Payable, we
introduce class Invoice, which implements interface Payable. We then modify
class Employee such that it also implements interface Payable.

Classes Invoice and employee both represent things for which the company must
be able to calculate a payment amount. Both classes implement the Payable
interface, so a program can invoke method getPaymentAmount on Invoice objects
and Employee objects alike.

The UML class diagram below shows the hierarchy used in our accounts payable
application. The hierarchy begins with interface Payable. The UML distinguishes
an interface from other classes by placing the word “interface” in (« and ») above
the interface name. The UML expresses the relationship between a class and an
interface through a relationship known as realization. A class is said to “realize,” or
implement, the methods of an interface. A class diagram models a realization as a
dashed arrow with a hollow arrowhead pointing from the implementing class to
the interface. The diagram indicates that classes Invoice and Employee each
realize (i.e., implement) interface Payable. Class Employee appears in italics,
indicating that it’s an abstract class. Concrete class SalariedEmployee extends
Employee and inherits its superclass’s realization relationship with interface
Payable.

Invoice Class:

Create class Invoice to represent a simple invoice that contains billing


information for only one kind of item. The class declares private instance
variables itemNumber, itemDescription, quantity and pricePerItem Class Invoice
also contains a constructor, get and set methods that manipulate the class’s
instance variables and a toString method that returns a String representation of
an Invoice object. Methods setQuantity and setPricePerItem ensure that quantity
and pricePerItem obtain only nonnegative values.

Class Employee:

We now modify class Employee such that it implements interface Payable. It does
not make sense to implement method getPaymentAmount in class Employee
because we cannot calculate the getPaymentAmount owed to a general Employee
—we must first know the specific type of Employee. This forced each Employee
concrete subclass to override getPaymentAmount with an implementation. The
Employee class will contain variables first name, last name and SSN.
SalariedEmployee class will contain variable Salary. Both class will have get and
set methods and constructors. toString method must also be implemented in
both parent and child classes which display the values of the class data members.

public interface Payable {

double getPaymentAmount();

}public class Invoice implements Payable {

private String itemNumber;

private String itemDescription;

private int quantity;

private double pricePerItem;

// Constructor

public Invoice(String itemNumber, String itemDescription, int quantity, double


pricePerItem) {

this.itemNumber = itemNumber;

this.itemDescription = itemDescription;

setQuantity(quantity);

setPricePerItem(pricePerItem);

// Getters and Setters

public String getItemNumber() {

return itemNumber;

public void setItemNumber(String itemNumber) {

this.itemNumber = itemNumber;
}

public String getItemDescription() {

return itemDescription;

public void setItemDescription(String itemDescription) {

this.itemDescription = itemDescription;

public int getQuantity() {

return quantity;

public void setQuantity(int quantity) {

if (quantity >= 0) {

this.quantity = quantity;

} else {

throw new IllegalArgumentException("Quantity must be non-negative");

public double getPricePerItem() {

return pricePerItem;

}
public void setPricePerItem(double pricePerItem) {

if (pricePerItem >= 0.0) {

this.pricePerItem = pricePerItem;

} else {

throw new IllegalArgumentException("Price per item must be non-negative");

// Implementation of getPaymentAmount from Payable interface

@Override

public double getPaymentAmount() {

return getQuantity() * getPricePerItem();

// toString method

@Override

public String toString() {

return String.format("Invoice: %s - %s - Quantity: %d - Price per item: $%.2f",

getItemNumber(), getItemDescription(), getQuantity(), getPricePerItem());

}public abstract class Employee implements Payable {

private String firstName;

private String lastName;

private String socialSecurityNumber;

// Constructor
public Employee(String firstName, String lastName, String socialSecurityNumber) {

this.firstName = firstName;

this.lastName = lastName;

this.socialSecurityNumber = socialSecurityNumber;

// Getters and Setters

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getSocialSecurityNumber() {

return socialSecurityNumber;

}
public void setSocialSecurityNumber(String socialSecurityNumber) {

this.socialSecurityNumber = socialSecurityNumber;

// Abstract method to be implemented by subclasses

@Override

public abstract double getPaymentAmount();

// toString method

@Override

public String toString() {

return String.format("Employee: %s %s - SSN: %s", getFirstName(), getLastName(),


getSocialSecurityNumber());

}public class SalariedEmployee extends Employee {

private double salary;

// Constructor

public SalariedEmployee(String firstName, String lastName, String


socialSecurityNumber, double salary) {

super(firstName, lastName, socialSecurityNumber);

setSalary(salary);

// Getter and Setter for salary

public double getSalary() {


return salary;

public void setSalary(double salary) {

if (salary >= 0.0) {

this.salary = salary;

} else {

throw new IllegalArgumentException("Salary must be non-negative");

// Implementation of getPaymentAmount from Payable interface

@Override

public double getPaymentAmount() {

return getSalary();

// toString method

@Override

public String toString() {

return String.format("%s - Salary: $%.2f", super.toString(), getSalary());

}public class PayableInterfaceTest {

You might also like