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

AIML - Java - Manual-2024-25

Uploaded by

lnlnarasimha2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

AIML - Java - Manual-2024-25

Uploaded by

lnlnarasimha2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

|| Jai Sri Gurudev ||

Adichunchanagiri Shikshana Trust(R.)


SJC INSTITUTE OF TECHNOLOGY

Department of Artificial Intelligence & Machine Learning

LABORATORY MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA


[BCS306A]

Prepared by

Prof. MUNIRAJU M
Assistant Professor
Department of Artificial Intelligence & Machine Learning
SJC Institute of Technology

2024-25
Sl no. Program
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
1
read from command line arguments).
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
2
JAVA main method to illustrate Stack operations.
A class called Employee, which models an employee with an ID, name and salary, is designed
as shown in the following class diagram. The method raiseSalary (percent) increases the salary
3
by the given percentage. Develop the Employee class and suitable main method for
demonstration.
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another point
at the given (x, y) coordinates
4
● An overloaded distance(MyPoint another) that returns the distance from this point to the
given MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin
(0,0) Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and
calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and
implement
the respective methods to calculate the area and perimeter of each shape.Develop the code for
the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all the methods
defined in the class
Develop a JAVA program to create a class named shape. Create three sub classes namely:
circle, triangle and square, each class has two member functions named draw () and erase ().
5
Demonstrate polymorphism concepts by developing suitable methods, defining member data
and main program.
Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend the
6
Shape class and implement the respective methods to calculate the area and perimeter of each
shape.
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width)
7 and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods
Develop a JAVA program to create an outer class with a function display. Create another class
8 inside the outer class named inner with a function called display and call the two functions in
the main class.
Develop a JAVA program to raise a custom exception (user defined exception) for
9
DivisionByZero using try, catch, throw and finally.
Develop a JAVA program to create a package named mypack and import & implement it in a
10
suitable class.
Write a program to illustrate creation of threads using runnable class. (start method start each
11 of the newly created thread. Inside the run method there is sleep() for suspend the thread for
500 milliseconds).
Develop a program to create a class MyThread in this class a constructor, call the base class
12 constructor, using super and start the thread. The run method of the class starts after this. It can
be observed that both main thread and created child thread are executed concurrently.
Object Oriented Programming with JAVA

Program 1: Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).

class matrixAddition
{
public static void main(String []args)
{
if (args.length != 1) {
System.out.println("Please provide the value of N as a command-line argument.");
return;
}
System.out.println(args[0]);
int N = Integer.parseInt(args[0]);

// Create two matrices of size N x N


int[][] matrixA = new int[N][N];
int[][] matrixB = new int[N][N];
int[][] resultMatrix = new int[N][N];

// Fill the matrices with random values for demonstration purposes


fillMatrix(matrixA);
fillMatrix(matrixB);

// Perform matrix addition


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}

// Display the matrices


System.out.println("Matrix A:");
displayMatrix(matrixA);

System.out.println("Matrix B:");
displayMatrix(matrixB);

System.out.println("Resultant Matrix (A + B):");


displayMatrix(resultMatrix);
}

// Method to fill a matrix with random values


public static void fillMatrix(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = (int) (Math.random() * 10); // Fill with random values between 0 and 9
}
}
}

// Method to display a matrix


public static void displayMatrix(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {

Dept of CSE (AI&ML), SJCIT 2024-25 Page 1


Object Oriented Programming with JAVA

System.out.print(matrix[i][j] + " ");


}
System.out.println();
}
System.out.println();

}
}

Output :

Dept of CSE (AI&ML), SJCIT 2024-25 Page 2


Object Oriented Programming with JAVA

Program 2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.

package stack;
import java.util.Scanner;
public class stack {
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;

public stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}

public void push(int value) {


if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}

public int pop() {


if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}

public void display() {


if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}

Dept of CSE (AI&ML), SJCIT 2024-25 Page 3


Object Oriented Programming with JAVA

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == MAX_SIZE - 1;
}

public static void main(String[] args) {


stack stack = new stack();
Scanner scanner = new Scanner(System.in);

int choice;

do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display Stack Contents");
System.out.println("5. Check if the stack is empty");
System.out.println("6. Check if the stack is full");
System.out.println("0. Exit");

System.out.print("Enter your choice: ");


choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 6:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();

Dept of CSE (AI&ML), SJCIT 2024-25 Page 4


Object Oriented Programming with JAVA

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 5


Object Oriented Programming with JAVA

Program 3. A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raiseSalary (percent) increases the
salary by the given percentage. Develop the Employee class and suitable main method for
demonstration.

public class Employee {


private int id;
private String name;
private double salary;

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


if (percent > 0) {
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
System.out.println(name + "'s salary raised by " + percent + "%. New salary: $" + salary);
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}

public String toString() {


return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}

public static void main(String[] args) {


// Creating an Employee object
Employee employee = new Employee(1, "John Doe", 50000.0);

// Displaying employee details


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

// Raising salary by 10%


employee.raiseSalary(10);

// Displaying updated employee details


System.out.println("\nEmployee Details after Salary Raise:");
System.out.println(employee);
}

Dept of CSE (AI&ML), SJCIT 2024-25 Page 6


Object Oriented Programming with JAVA

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 7


Object Oriented Programming with JAVA

Program 4 A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another point at
the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test
all the methods defined in the class.

public class MyPoint {


private int x;
private int y;

// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}

// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

// Set both x and y


public void setXY(int x, int y) {
this.x = x;
this.y = y;
}

// Get x and y in a 2-element int array


public int[] getXY() {
return new int[]{x, y};
}

// Return a string description of the instance in the format "(x, y)"


public String toString() {
return "(" + x + ", " + y + ")";
}

// Calculate distance from this point to another point at (x, y) coordinates


public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}

// Calculate distance from this point to another MyPoint instance (another)


public double distance(MyPoint another) {

Dept of CSE (AI&ML), SJCIT 2024-25 Page 8


Object Oriented Programming with JAVA

return distance(another.x, another.y);


}

// Calculate distance from this point to the origin (0,0)


public double distance() {
return distance(0, 0);
}
}

public class TestMyPoint {


public static void main(String[] args) {
// Creating MyPoint objects using different constructors
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);

// Testing setXY and getXY methods


point1.setXY(1, 2);
System.out.println("Point1 coordinates after setXY: " + point1.getXY()[0] + ", " +
point1.getXY()[1]);

// Testing toString method


System.out.println("Point2 coordinates: " + point2.toString());

// Testing distance methods


System.out.println("Distance from Point1 to Point2: " + point1.distance(point2));
System.out.println("Distance from Point2 to Origin: " + point2.distance());
}
}

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 9


Object Oriented Programming with JAVA

Program 5. Develop a JAVA program to create a class named shape. Create three sub classes
namely: circle, triangle and square, each class has two member functions named draw () and erase ().
Demonstrate polymorphism concepts by developing suitable methods, defining member data and
main program.

class Shape {
protected String name;

public Shape(String name) {


this.name = name;
}

public void draw() {


System.out.println("Drawing a " + name);
}

public void erase() {


System.out.println("Erasing a " + name);
}
}

class Circle extends Shape {


private double radius;

public Circle(String name, double radius) {


super(name);
this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}

@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}

class Triangle extends Shape {


private double base;
private double height;

public Triangle(String name, double base, double height) {


super(name);
this.base = base;
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}

@Override

Dept of CSE (AI&ML), SJCIT 2024-25 Page 10


Object Oriented Programming with JAVA

public void erase() {


System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}

class Square extends Shape {


private double side;

public Square(String name, double side) {


super(name);
this.side = side;
}

@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}

@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}

public class ShapeDemo {


public static void main(String[] args) {
Shape[] shapes = new Shape[3];

shapes[0] = new Circle("Circle", 5.0);


shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);

for (Shape shape : shapes) {


shape.draw();
shape.erase();
System.out.println();
}
}
}

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 11


Object Oriented Programming with JAVA

Program 6. Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend the
Shape class and implement the respective methods to calculate the area and perimeter of each shape.

abstract class Shape {


abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shape {


private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}

public class ShapeDemo {


public static void main(String[] args) {
// Creating Circle and Triangle objects
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);

Dept of CSE (AI&ML), SJCIT 2024-25 Page 12


Object Oriented Programming with JAVA

// Calculating and displaying area and perimeter


System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

System.out.println("\nTriangle Area: " + triangle.calculateArea());


System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}

Output:

Dept of CSE (AI&ML), SJCIT 2024-25 Page 13


Object Oriented Programming with JAVA

Program 7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int
width) and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods.

interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Rectangle class implementing Resizable interface


class Rectangle implements Resizable {
private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

// Implementation of Resizable interface


@Override
public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}

@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}

// Additional methods for Rectangle class


public int getWidth() {
return width;
}

public int getHeight() {


return height;
}

public void displayInfo() {


System.out.println("Rectangle: Width = " + width + ", Height = " + height);
}
}

// Main class to test the implementation


public class ResizeDemo {
public static void main(String[] args) {
// Creating a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);

// Displaying the original information


System.out.println("Original Rectangle Info:");
rectangle.displayInfo();

// Resizing the rectangle

Dept of CSE (AI&ML), SJCIT 2024-25 Page 14


Object Oriented Programming with JAVA

rectangle.resizeWidth(15);
rectangle.resizeHeight(8);

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}

Out put

Dept of CSE (AI&ML), SJCIT 2024-25 Page 15


Object Oriented Programming with JAVA

Program 8. Develop a JAVA program to create an outer class with a function display. Create
another class inside the outer class named inner with a function called display and call the two
functions in the main class.

class Outer {
void display() {
System.out.println("Outer class display method");
}

class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args) {
// Create an instance of the Outer class
Outer outer = new Outer();

// Call the display method of the Outer class


outer.display();

// Create an instance of the Inner class (nested inside Outer)


Outer.Inner inner = outer.new Inner();

// Call the display method of the Inner class


inner.display();
}
}

class Outer {
void display() {
System.out.println("Outer class display method");
}

class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args) {
// Create an instance of the Outer class
Outer outer = new Outer();

// Call the display method of the Outer class


outer.display();

// Create an instance of the Inner class (nested inside Outer)


Outer.Inner inner = outer.new Inner();
// Call the display method of the Inner class
inner.display();
}

Dept of CSE (AI&ML), SJCIT 2024-25 Page 16


Object Oriented Programming with JAVA

}
Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 17


Object Oriented Programming with JAVA

Program 9.Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

class DivisionByZeroException extends Exception {


public DivisionByZeroException(String message) {
super(message);
}
}

public class CustomExceptionDemo {


// Method to perform division and throw custom exception if denominator is zero
static double divide(int numerator, int denominator) throws DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Cannot divide by zero!");
}
return (double) numerator / denominator;
}

public static void main(String[] args) {


int numerator = 10;
int denominator = 0;

try {
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 18


Object Oriented Programming with JAVA

Program 10. Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.

package mypack;

public class MyPackageClass {


public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}

// New utility method


public static int addNumbers(int a, int b) {
return a + b;
}
}

import mypack.MyPackageClass;
//import mypack.*;

public class PackageDemo {


public static void main(String[] args) {
// Creating an instance of MyPackageClass from the mypack package
MyPackageClass myPackageObject = new MyPackageClass();

// Calling the displayMessage method from MyPackageClass


myPackageObject.displayMessage();

// Using the utility method addNumbers from MyPackageClass


int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);
}
}

Dept of CSE (AI&ML), SJCIT 2024-25 Page 19


Object Oriented Programming with JAVA

Dept of CSE (AI&ML), SJCIT 2024-25 Page 20


Object Oriented Programming with JAVA

11. Write a program to illustrate creation of threads using runnable class. (start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).

class MyRunnable implements Runnable {


private volatile boolean running = true;

@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}

public void stopThread() {


running = false;
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
// Create five instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();

// Create five threads and associate them with MyRunnable instances


Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);

// Start the threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();

// Sleep for a while to allow the threads to run


try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

Dept of CSE (AI&ML), SJCIT 2024-25 Page 21


Object Oriented Programming with JAVA

// Stop the threads gracefully


myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
}
}

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 22


Object Oriented Programming with JAVA

Program 12. Develop a program to create a class MyThread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts after this. It
can be observed that both main thread and created child thread are executed concurrently.

class MyThread extends Thread {


// Constructor calling base class constructor using super
public MyThread(String name) {
super(name);
start(); // Start the thread in the constructor
}

// The run method that will be executed when the thread starts
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}

public class ThreadConcurrentExample {


public static void main(String[] args) {
// Create an instance of MyThread
MyThread myThread = new MyThread("Child Thread");

// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}

Output

Dept of CSE (AI&ML), SJCIT 2024-25 Page 23


Object Oriented Programming with JAVA

VIVA QUESTIONS AND ANSWERS

1. What is Object Oriented Programming?


Object-Oriented Programming(OOPs) is a type of programming that is based on objects rather than just
functions and procedures. Individual objects are grouped into classes. OOPs implements real-world entities
like inheritance, polymorphism, hiding, etc into programming. It also allows binding data and code
together.

2. Why use OOPs?


 OOPs allows clarity in programming thereby allowing simplicity in solving complex problems
 Code can be reused through inheritance thereby reducing redundancy
 Data and code are bound together by encapsulation
 OOPs allows data hiding, therefore, private data is kept confidential
 Problems can be divided into different parts making it simple to solve
 The concept of polymorphism gives flexibility to the program by allowing the entities to have
multiple forms

3. What are the main features of OOPs?


 Inheritance
 Encapsulation
 Polymorphism
 Data Abstraction

4. What is an object?
An object is a real-world entity which is the basic unit of OOPs for example chair, cat, dog, etc. Different
objects have different states or attributes, and behaviors.

5. What is a class?
A class is a prototype that consists of objects in different states and with different behaviors. It has a
number of methods that are common the objects present within that class.
6. What is the difference between a class and a structure?
Class: User-defined blueprint from which objects are created. It consists of methods or set of instructions
that are to be performed on the objects.
Structure: A structure is basically a user-defined collection of variables which are of different data types.

7. Can you call the base class method without creating an instance?
Yes, you can call the base class without instantiating it if:
 It is a static method
 The base class is inherited by some other subclass

Dept of CSE (AI&ML), SJCIT 2024-25 Page 24


Object Oriented Programming with JAVA

8. What is the difference between a class and an object?

Object Class
A class is basically a template or a blueprint within
A real-world entity which is an instance of a class
which objects can be created
An object acts like a variable of the class Binds methods and data together into a single unit
An object is a physical entity A class is a logical entity
Objects take memory space when they are created A class does not take memory space when created
Objects can be declared as and when required Classes are declared just once

9. What is inheritance?
Inheritance is a feature of OOPs which allows classes inherit common properties from other classes. For
example, if there is a class such as ‘vehicle’, other classes like ‘car’, ‘bike’, etc can inherit common
properties from the vehicle class. This property helps you get rid of redundant code thereby reducing the
overall size of the code.
10. What are the different types of inheritance?
 Single inheritance
 Multiple inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Hybrid inheritance

11. What is encapsulation?


Encapsulation refers to binding the data and the code that works on that together in a single unit. For
example, a class. Encapsulation also allows data-hiding as the data specified in one class is hidden from
other classes.
12. What are ‘access specifiers’?
Access specifiers or access modifiers are keywords that determine the accessibility of methods, classes, etc
in OOPs. These access specifiers allow the implementation of encapsulation. The most common access
specifiers are public, private and protected. However, there are a few more which are specific to the
programming languages.
13. What is the difference between public, private and protected access modifiers?

Accessibility from own Accessibility from


Name Accessibility from world
class derived class
Public Yes Yes Yes
Private Yes No No
Protected Yes Yes No

14. What are virtual functions?


Virtual functions are functions that are present in the parent class and are overridden by the subclass. These
functions are used to achieve runtime polymorphism.
15. What are pure virtual functions?
Pure virtual functions or abstract functions are functions that are only declared in the base class. This

Dept of CSE (AI&ML), SJCIT 2024-25 Page 25


Object Oriented Programming with JAVA

means that they do not contain any definition in the base class and need to be redefined in the subclass.

16. What is a constructor?


A constructor is a special type of method that has the same name as the class and is used to initialize
objects of that class.

17. What is a destructor?


A destructor is a method that is automatically invoked when an object is destroyed. The destructor also
recovers the heap space that was allocated to the destroyed object, closes the files and database connections
of the object, etc.

18. Types of constructors


Types of constructors differ from language to language. However, all the possible constructors are:
 Default constructor
 Parameterized constructor
 Copy constructor
 Static constructor
 Private constructor
19. What is a copy constructor?
A copy constructor creates objects by copying variables from another object of the same class. The main
aim of a copy constructor is to create a new object from an existing one.
20. What is the use of ‘finalize’?
Finalize as an object method used to free up unmanaged resources and cleanup before Garbage
Collection(GC). It performs memory management tasks.

Dept of CSE (AI&ML), SJCIT 2024-25 Page 26

You might also like