Lab Manual Ooj
Lab Manual Ooj
DEPARTMENT OF COMPUTER
SCIENCE AND ENGINEERING
LABORATORY MANUAL
The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
The manual of Object-oriented programming has been prepared for B.E Artificial
intelligence and machine learning students. Object-oriented programming is
increasingly becoming top priority choice of IT industry especially industries involve
in software development at system level.
The manual prepared for proper development of Java skills among the students. The
manual contains programs and their solutions for easy and quick understanding of
students
ABOUT
The Department of Computer Science and Engineering was established in the year 2021.The department
offer undergraduate in Computer Science and Engineering. The department has a very good
infrastructure and faculty to provide excellent education to meet the industry standards.
Today, the department caters to the needs of more than 180 UG students. It houses state of the art
computing facilities with high end servers which support the LAN, provide a Linux/Unix environment,
also provides exclusive library facility to its students and boasts of well trained and experienced faculty
teaching the departments various courses in the areas of Computer Networks, Computer Architecture,
Database Systems, Microcontroller, Operating Systems, Design and Analysis of Algorithms and
Software Engineering.
The department lays stress on the practical and application-based aspects through laboratories, seminars,
group discussions, viva-voce and project work, keeping pace with the growth in Computer Science &
Engineering and AI technology.
Students are provided with opportunities to conduct experiments on innovative ideas, blending sound the
or ethical knowledge with practical experience. This comprehensive approach prepares them for a broad
spectrum of challenging roles in the field of Computer Science & Engineering and AI, including:
[Type text]
Page 4
PROGRAM OUTCOMES
[Type text]
Page 5
EAST WEST INSTITUTE OF TECHNOLOGY
Department of Computer Science and Engineering
Prepared by,
[Type text]
Page 6
Object Oriented Program Programming with java
COURSE DETAILS
Course Name: Oriented Programming with JAVA Laboratory
Course Code:
BCS306A Course
Credit: 2
COURSE OBJECTIVE
1. To learn primitive constructs JAVA programming language.
2. To understand Object Oriented Programming Features of JAVA.
3. To gain knowledge on: packages, multithreaded programming and exceptions.
COURSE OUTCOME
BCS306A -1. Demonstrate proficiency in writing simple programs involving branching and looping
structures.
BCS306A -2. Design a class involving data members and methods for the given scenario.
BCS306A -3. Apply the concepts of inheritance and interfaces in solving real world
problems. BCS306A -4. Use the concept of packages and exception handling in solving
complex problem
BCS306A -5. Apply concepts of multithreading, autoboxing and enumerations in program development
CO-PO&PSOMAPPING
COURSE P P P P P P P P P PO PO PO
OUTCO O1 O2 O3 O O5 O6 O7 O8 O9 10 11 12
ME
4
BCS306A 3 3 3 -- 3 -- -- -- 3 2 -- 3
.1
BCS306A 3 3 3 -- 3 -- -- -- 3 2 -- 3
.2
BCS306A 3 3 3 2 3 -- -- -- 3 2 -- 3
.3
BCS306A 3 3 3 2 3 -- -- -- 3 3 2 3
.4
BCS306A 3 3 3 2 3 -- -- -- 3 2 2 3
.5
OOJ P P P P P P P P P PO PO PO
Object Oriented Program Programming with java
Laborator O1 O2 O3 O O5 O6 O7 O8 O9 10 11 12
y
BCS30 4
6A
3 3 3 2 3 -- -- -- 3 2 2 3
Object Oriented Program Programming with java
2 Program 5
Execution
TOTAL 1
0
Lab Rubrics
Students’ performance in Laboratory course is evaluated using rubrics defined by the program.
Rubrics for evaluating a lab test in programming lab are displayed in the following table.
Student’s ability in developing programs and testing the program, documenting the work done
through lab record, etc are evaluated continuously during all lab sessions.
SYLLABUS
LIST OF PROGRAMS
Sl.N Name of the COS POS
o experiments
1 Develop a JAVA program to add TWO matrices of suitable order CO1 PO1,P
N (The value of N should be read from command line 02,
arguments). PO3
2 Develop a stack class to hold a maximum of 10 integers CO1 PO1,PO2,PO
with suitable methods. Develop a JAVA main method to 3
illustrate Stack operations.
3 A class called Employee, which models an employee with an ID, CO1 PO1,PO2,PO
name and salary, is designed as shown in the following class 3
diagram. The method raiseSalary (percent) increases the salary by
the given percentage. Develop the Employee class and suitable
main method for demonstration.
4 A class called MyPoint, which models a 2D point with x and y CO2 PO1,P
coordinates, is designed as follows: O2,
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the PO3
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.
Object Oriented Program Programming with java
PROGRAMS
1. Develop a JAVA program to add TWO matrices of suitable order N (The value
of N should be read from command line arguments).
// Java program for addition of two
matrices import java.io.*;
class GFG {
// Function to print Matrix
static void printMatrix(int
M[][], int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i+
+) { for (int j = 0; j <
colSize; j++)
System.out.print(M[i][j] + "
"); System.out.println();
}
}
// Function to add the two matrices
// and store in matrix C
static int[][] add(int A[][], int
B[][], int size)
{
int i, j;
int C[][] = new int[size]
[size]; for (i = 0; i < size;
i++)
for (j = 0; j < size; j+
+) C[i][j] = A[i][j] +
B[i][j];
return C;
}
// Driver code
public static void main(String[] args)
{
int size = 4;
int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix
A:"); printMatrix(A, size,
size);
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
Object Oriented Program Programming with java
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix
B:"); printMatrix(B, size,
size);
// Add the two matrices
int C[][] = add(A, B, size);
// Print the result System.out.println("\
nResultant Matrix:"); printMatrix(C,
size, size);
}
}
Output:
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
ALGORITHM:
Algorithm:
1. Parse the command line argument to get the size N.
2. Define two matrices of size N×N to store the input values.
3. Define a third matrix of size N×N to store the sum of the two input matrices.
4. For each element in the matrices:
● Read the values for the first matrix.
● Compute the sum of corresponding elements from both matrices and store the result in the result
matrix.
5. Print the result matrix.
Explanation:
1. Command Line Argument Parsing:
● The program expects the matrix size N as a command line argument. If no argument is provided or
the argument is invalid, the program will ask the user to provide it correctly.
2. Reading Matrix Elements:
● The program uses a Scanner to read the matrix elements from the user.
● The user is prompted to input the values for two matrices, matrixA and matrixB, each with N×N
elements.
3. Matrix Addition:
● The program iterates over each element of the matrices, adds the corresponding elements, and stores
the result in resultMatrix.
4. Displaying the Result:
● Finally, the result matrix (sum of the two matrices) is displayed in a formatted way.
Notes:
● The size N must be the same for both matrices in order for the addition to work.
● The program assumes that the input is valid (no need for further validation).
2.Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
// Java code for stack
import java.util.*;
class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer>
stack)
{
Object Oriented Program Programming with java
for(int i = 0; i < 10; i++)
{
stack.push(i);
}
}
// Popping element from the top of the
stack static void
stack_pop(Stack<Integer> stack)
{
System.out.println("Pop
Operation:"); for(int i = 0; i < 10;
i++)
{
Integer y = (Integer)
stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the
stack static void
stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " +
element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer)
stack.search(element); if(pos == -1)
System.out.println("Element not
found"); else
System.out.println("Element is found at position: " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new
Stack<Integer>(); stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
Output
Object Oriented Program Programming with java
Here is an algorithm to perform basic stack operations like push, pop, peek, and is
Empty:Definitions
● A stack is a Last-In-First-Out (LIFO) data structure.
● Operations:
1. Push: Add an element to the top of the stack.
2. Pop: Remove and return the top element.
3. Peek: Return the top element without removing it.
4. isEmpty: Check if the stack is empty.
Algorithm
Initialize Stack
Push Operation
1. Input: element
2. Increment the top pointer: top = top + 1
3. Add element at position top in S: S[top] = element
Explanation:
In Java, a stack is a data structure that follows the Last In, First Out (LIFO) principle, meaning the last
element added to the stack is the first one to be removed. Java provides a built-in Stack class in the
java.util package to perform stack operations. Below are common stack operations and examples of how to
use them:
Object Oriented Program Programming with java
1. Creating a Stack
java
Copy code
import java.util.Stack;
2. Basic Operations
java
Copy code
stack.push(10); // Adds 10 to the stack
stack.push(20); // Adds 20 to the stack
java
Copy code
int topElement = stack.pop(); // Removes and returns the top element (20)
java
Copy code
int topElement = stack.peek(); // Returns the top element (10) without removing it
SYSTEM REQUIREMENTS:
Object Oriented Program Programming with java
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Object Oriented Program Programming with java
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.
import
java.io.*;
import
java.util.*;
public class
Employee
{ private int id;
private String
name; private
double salary;
// Constructor
public Employee(int id, String name, double
salary) { this.id = id;
this.name =
name;
this.salary =
salary;
}
// Getter
methods
public int
getId() {
return id;
}
public String
getName() { return
name;
}
public double
getSalary() { return
salary;
}
// Method to raise salary by a given
percentage public void raiseSalary(double
percent) {
if (percent > 0) {
double increaseAmount = salary * (percent /
100); salary += increaseAmount;
System.out.println(name + "'s salary has been increased by " + percent + "%. New salary: $" + salary);
} else {
Object Oriented Program Programming with java
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}
public static void main(String[] args) {
// Create an Employee object
Employee employee1 = new Employee(1, "John Doe", 50000.0);
// Display initial employee information
System.out.println("Initial Employee Information:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " +
employee1.getName()); System.out.println("Salary:
$" + employee1.getSalary());
// Raise the salary by 10%
employee1.raiseSalary(10);
// Display updated employee information
System.out.println("\nUpdated Employee
Information:"); System.out.println("ID: " +
employee1.getId()); System.out.println("Name: " +
employee1.getName()); System.out.println("Salary:
$" + employee1.getSalary());
}
}
Output :
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Algorithm:
1. Define the Employee class:
● Attributes:
● Initialize the attributes (id, name, salary) when a new employee object is created.
Object Oriented Program Programming with java
3. Define the raiseSalary method:
● This method will return a string representation of the employee object to display the employee's
details.
5. Create a main method (or test script):
Explanation:
In this task, you're asked to design a class called Employee, which models an employee with three key
attributes: ID, name, and salary. The class will also have a method raiseSalary(percent) that increases
the salary of an employee by a given percentage. Additionally, a main method is required to demonstrate how
this class works.
Here’s a breakdown of what you need to do:
1. Attributes:
● ID: This could be an integer representing the unique ID for each employee.
2. Methods:
● raiseSalary(percent): This method takes a percentage as an argument, calculates the raise based on the
current salary, and then updates the salary. The formula for increasing the salary by a percentage is:
salary salarynew salary=current salary×(1+100percent)
● Constructor: A constructor (__init__ in Python) to initialize the attributes (ID, name, and salary).
Object Oriented Program Programming with java
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.
import
java.io.*;
import
java.util.*;
class MyPoint
Object Oriented Program Programming with java
{
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;
}
// Method to set both x and
y public void setXY(int x,
int y) {
this.x
= x;
this.y
= y;
}
// Method to get x and y in a 2-element int
array public int[] getXY() {
int[] coordinates = {x,
y}; return
coordinates;
}
// Method to return a string description of the
instance @Override
public String toString() {
return "(" + x + ", " + y + ")";
}
// Method to calculate distance to another point with given
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);
}
// Overloaded method to calculate distance to another MyPoint
instance public double distance(MyPoint another) {
return distance(another.x, another.y);
}
// Overloaded method to calculate distance to the origin
Object Oriented Program Programming with java
(0,0) public double distance() {
return distance(0, 0);
}
}
public class TestMyPoint {
public static void main(String[] args) {
// Create MyPoint objects
MyPoint point1 = new
MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Test setXY and getXY
methods point1.setXY(5, 6);
int[] coordinates = point1.getXY();
System.out.println("Point1 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")");
// Test toString method
System.out.println("Point2 coordinates: " + point2);
// Test distance methods
System.out.println("Distance between Point1 and (1, 1): " + point1.distance(1, 1));
System.out.println("Distance between Point1 and Point2: " +
point1.distance(point2)); System.out.println("Distance between Point2 and the
origin: " + point2.distance());
}
}
Output :
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Algorithm:
python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Initialize the stack as an empty list
def is_empty(self):
Object Oriented Program Programming with java
"""
Returns True if the stack is empty, else False.
"""
return len(self.stack) == 0
def pop(self):
"""
Removes and returns the item from the top of the stack.
Raises IndexError if the stack is empty.
"""
if self.is_empty():
raise IndexError("pop from empty stack")
return self.stack.pop()
def peek(self):
"""
Returns the item at the top of the stack without removing it.
Raises IndexError if the stack is empty.
"""
if self.is_empty():
raise IndexError("peek from empty stack")
return self.stack[-1]
def size(self):
"""
Returns the number of items in the stack.
"""
return len(self.stack)
def __str__(self):
"""
Returns a string representation of the stack.
"""
return f"Stack(top -> {', '.join(map(str, self.stack[::-1]))})"
Explanation:
1. __init__(): Initializes an empty list to represent the stack.
2. is_empty(): Checks if the stack is empty.
3. push(item): Adds an item to the top of the stack.
4. pop(): Removes and returns the item from the top of the stack. Raises an error if the stack is empty.
5. peek(): Returns the top item without removing it. Raises an error if the stack is empty.
6. size(): Returns the number of items in the stack.
7. __str__(): Provides a string representation of the stack, with the top of the stack listed first.
Example Usage:
python
Copy code
# Create a stack
s = Stack()
This implementation ensures efficient stack operations with O(1) complexity for each method.
4o mini
5. Develop a JAVA program to create a class named shape. Create three sub classes
Object Oriented Program Programming with java
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.
import
java.io.*;
import
java.util.*;
class Shape {
public void draw()
{ System.out.println("Drawing a
shape");
}
public void erase()
{ System.out.println("Erasing a
shape");
}
}
class Circle extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
circle");
}
@Override
public void erase()
{ System.out.println("Erasing a
circle");
}
}
class Triangle extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
triangle");
}
@Override
public void erase()
{ System.out.println("Erasing a
triangle");
}
}
class Square extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
square");
}
@Override
public void erase()
{ System.out.println("Erasing a
Object Oriented Program Programming with java
square");
}
}
public class ShapeDemo {
public static void main(String[] args) {
Output :
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Algorithm:
1. Define a base class Shape:
● These methods will be abstract because the actual implementation will be provided by the
subclasses.
2. Create subclasses Circle, Triangle, and Square:
● Override the draw() and erase() methods in each subclass with their specific implementations.
3. Use polymorphism:
Object Oriented Program Programming with java
● Create an array or list of Shape references in the main method.
● Use the draw() and erase() methods on the Shape references, which will invoke the
overridden methods of the respective subclasses.
Explanation:
1. Shape Class (Super Class)
The Shape class is the base class for all the shapes. It contains the draw() and erase() methods, but they are
just placeholders (abstract methods in this case). We don't implement these methods here because each subclass
will provide its own implementation.
java
Copy code
abstract class Shape {
// Abstract method to draw the shape
public abstract void draw();
● abstract keyword means the class cannot be instantiated directly and must be subclassed.
● The draw() and erase() methods are abstract and don't have bodies because each shape has its own
way of drawing and erasing.
The Circle class extends Shape and provides implementations for the draw() and erase() methods.
java
Copy code
class Circle extends Shape {
// Draw method specific to Circle
public void draw() {
System.out.println("Drawing a Circle");
}
● The draw() method prints a message to indicate drawing a circle, and the erase() method does the
same for erasing the circle.
java
Copy code
class Triangle extends Shape {
// Draw method specific to Triangle
public void draw() {
System.out.println("Drawing a Triangle");
}
● Triangle implements its own version of the draw() and erase() methods.
The Square class, like the other subclasses, extends Shape and implements the draw() and erase()
methods.
java
Copy code
class Square extends Shape {
// Draw method specific to Square
public void draw() {
System.out.println("Drawing a Square");
}
● Square provides its own definitions for the draw() and erase() methods.
In the main program, polymorphism is demonstrated by creating references of type Shape but instantiating objects
of the subclasses (Circle, Triangle, and Square). This is where the concept of polymorphism (method
overriding) comes into play, as the draw() and erase() methods will be called based on the actual object type
(not the reference type).
java
Copy code
public class Main {
public static void main(String[] args) {
// Creating objects of the derived classes
Shape circle = new Circle();
Shape triangle = new Triangle();
Shape square = new Square();
// Polymorphism in action: the correct method is called based on the object type
Object Oriented Program Programming with java
circle.draw(); // Outputs: Drawing a Circle
circle.erase(); // Outputs: Erasing the Circle
● Polymorphism is demonstrated by calling the draw() and erase() methods on references of type
Shape, but the actual methods executed are from the Circle, Triangle, and Square classes,
depending on the object assigned to the reference.
● The actual method that gets called at runtime is determined by the type of object that the reference points to.
This is the key concept of method overriding in Java.
● Inheritance: The Circle, Triangle, and Square classes inherit from the Shape class.
● Method Overriding: The draw() and erase() methods are overridden in each subclass.
● Polymorphism: The ability to call the same method (draw() and erase()) on different types of objects
and have the correct version of the method executed based on the actual object type.
In summary, this program uses inheritance, method overriding, and polymorphism to create a hierarchy of shapes
and demonstrate how Java resolves which method to call at runtime based on the actual object type.
Object Oriented Program Programming with java
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.
import java.io.*;
import java.util.*;
abstract class
Shape {
// Abstract methods to calculate area and
perimeter public abstract double
calculateArea();
public abstract double calculatePerimeter();
}
class Circle extends
Shape { private double
radius;
// Constructor for Circle
public Circle(double
radius) { this.radius =
radius;
}
// Implementation of abstract
methods @Override
public double
calculateArea() { return
Math.PI * radius * radius;
}
@Override
public double
calculatePerimeter() { return 2 *
Math.PI * radius;
}
}
class Triangle extends Shape
{ private double side1, side2,
side3;
// Constructor for Triangle
Object Oriented Program Programming with java
public Triangle(double side1, double side2, double
side3) { this.side1 = side1;
this.side2 =
side2;
this.side3 =
side3;
}
// Implementation of abstract
methods @Override
public double calculateArea() {
// Heron's formula for area of a
triangle double s = (side1 + side2 +
side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double
calculatePerimeter() { return
side1 + side2 + side3;
}
}
Output :
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
● Implement the calculateArea() method to compute the area of the circle using the formula:
Area=π×r2
● Implement the calculatePerimeter() method to compute the perimeter of the circle using the
formula: Perimeter=2×π×r
3. Create the Triangle subclass:
● Declare attributes for the three sides of the triangle (e.g., side1, side2, side3).
● Create instances of Circle and Triangle and call the calculateArea() and
calculatePerimeter() methods to display the results.
Explanation:
Here’s an explanation for the Java program that involves creating an abstract
class Shape with abstract methods calculateArea() and calculatePerimeter(),
and creating subclasses Circle and Triangle that extend the Shape class and
implement these methods:
1. Abstract Class Shape
● An abstract class in Java is a class that cannot be instantiated directly. It is used to define a common base
for subclasses.
● The Shape class contains abstract methods calculateArea() and calculatePerimeter().
These methods have no implementation in the abstract class but must be implemented by any subclass.
● The Shape class might also have common attributes, but its main purpose here is to act as a blueprint for
other shapes like Circle and Triangle.
2. Abstract Methods
● calculateArea(): This method will be implemented by each subclass to calculate the area of the
respective shape.
● calculatePerimeter(): This method will be implemented by each subclass to calculate the perimeter
of the respective shape.
● Abstract classes allow you to define methods that must be implemented by subclasses, ensuring that all
shapes will have a way to calculate their area and perimeter, regardless of the specific type of shape.
Output :
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
To develop a Java program that defines an interface Resizable with methods for resizing the width and
height of an object, and then creates a Rectangle class that implements the interface, you can follow
these steps:
Algorithm
1. Define the Resizable interface:
Object Oriented Program Programming with java
●The interface will have two methods: resizeWidth(int width) and resizeHeight(int
height).
2. Create the Rectangle class:
● The Rectangle class should have two properties: width and height.
●It should implement the Resizable interface by providing implementations for the
resizeWidth and resizeHeight methods.
3. Create a constructor and methods in the Rectangle class:
● Create an instance of Rectangle, display its initial size, resize it using the methods from
Resizable, and display the updated size.
Explanation:
1. Resizable Interface:
● The Rectangle class implements the Resizable interface, which requires it to provide
implementations for resizeWidth and resizeHeight.
● It also has a constructor to initialize the width and height of the rectangle and a `display Dimension
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.
import
java.io.*;
import
java.util.*;
class
OuterClass {
// Outer class display
function public void
display() {
System.out.println("OuterClass display function");
}
// Inner class
class
Object Oriented Program Programming with java
InnerClass {
// Inner class display
function public void
display() {
System.out.println("InnerClass display function");
}
}
}
public class MainClass {
public static void main(String[] args) {
// Create an instance of OuterClass
OuterClass outerObject = new
OuterClass();
// Call the display function of the outer
class outerObject.display();
// Create an instance of InnerClass (nested class)
OuterClass.InnerClass innerObject = outerObject.new
InnerClass();
// Call the display function of the inner
class innerObject.display();
}}
Output:
arduino
Copy code
This is the display method of the Outer class.
This is the display method of the Inner class.
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Here is the algorithm for creating a Java program with an outer class containing an inner class, where both
classes have a display function:
Algorithm:
1. Define the Outer Class:
● Inside the outer class, define a public static inner class (e.g., Inner).
Inside the inner class, define a method display() that prints a message indicating it belongs to the
●
inner class.
3. Main Class (Main Method):
Object Oriented Program Programming with java
● In the main() method, create an instance of the outer class.
● Call the display() method of the outer class.
● Create an instance of the inner class and call its display() method.
Explanation:
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
import
java.io.*;
import
java.util.*;
// Custom exception class
class DivisionByZeroException extends Exception
{ public DivisionByZeroException(String
message) {
super(message);
}
}
public class CustomExceptionDemo
{ public static void main(String[]
Object Oriented Program Programming with java
args) {
try {
// Call a method that may throw the custom
exception divideNumbers(10, 0);
} catch (DivisionByZeroException e) {
// Catch the custom exception and handle it
System.out.println("Error: " + e.getMessage());
} finally {
// Code in the finally block will always be executed, whether an exception occurs or
not System.out.println("Finally block executed");
}
}
// Method that may throw the custom exception
private static void divideNumbers(int numerator, int denominator) throws
DivisionByZeroException { try {
// Attempt to perform division
int result = numerator / denominator;
// Display the result if successful
System.out.println("Result of division: " +
result);
} catch (ArithmeticException e) {
// Catch the ArithmeticException (division by zero) and throw a custom
exception throw new DivisionByZeroException("Cannot divide by zero");
}
}
}
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
Object Oriented Program Programming with java
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Here's an algorithm to create a Java program that raises a custom exception (user-defined exception) for a division by zero
scenario using try, catch, throw, and finally blocks.
Algorithm:
1. Define a Custom Exception Class:
● In the main class, define a method divide that accepts two parameters (dividend and divisor).
● Inside the divide method, check if the divisor is zero.
If true, throw the custom DivisionByZeroException using throw and provide an
●
appropriate message.
● If the divisor is not zero, perform the division and return the result.
3. Use try-catch-finally Block:
● In the main method, call the divide method inside a try block.
● Catch the DivisionByZeroException using a catch block and display the error message.
● Use a finally block to print a message indicating that the program execution has completed (for
resource cleanup or final statements).
Object Oriented Program Programming with java
Explanation:
1. DivisionByZeroException Class: This is a user-defined exception that inherits from Exception. It
accepts a custom error message when the exception is thrown.
2. Divide Method: The method checks if the divisor is zero and throws the custom exception if it is.
Otherwise, it performs the division and returns the result.
3. Main Method:
● A try block calls the divide method.
● If the divisor is zero, the DivisionByZeroException is thrown and caught in the catch
block, which displays the error message.
● The finally block always runs, printing a message indicating the completion of program
execution.
Object Oriented Program Programming with java
10. Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.
Output
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
● In Java, packages are typically stored in directories, so we will create a directory named mypack to
hold our classes.
2. Step 2: Create a class MyClass inside the mypack package.
● In this class, define some methods that we can later use in another class.
3. Step 3: Create another class MainClass outside the mypack package.
Explanation:
1. Step 1: Save MyClass.java inside a folder named mypack.
3. Step 3: Open a terminal/command prompt and navigate to the directory where MainClass.java is
located.
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 String
threadName;
// Constructor to initialize the thread
name public MyRunnable(String
name) {
this.threadName = name;
}
// Run method to be executed when the thread
starts public void run() {
try {
for (int i = 0; i < 5; i++)
{ System.out.println(threadName + ": Count
" + i);
// Suspend the thread for 500
milliseconds Thread.sleep(500);
}
} catch (InterruptedException e)
{ System.out.println(threadName + "
interrupted.");
}
System.out.println(threadName + "
exiting."); } } public class RunnableThreadExample
{
public static void main(String[] args) {
// Create two threads using the MyRunnable class
Thread thread1 = new Thread(new MyRunnable("Thread
1")); Thread thread2 = new Thread(new
MyRunnable("Thread 2"));
// Start the
threads
thread1.start();
thread2.start();
}}
Outp
ut ;
Object Oriented Program Programming with java
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Object Oriented Program Programming with java
Algorithm:
To create threads using the Runnable interface in Java, you'll need to follow these steps:
1. Implement the Runnable Interface: Create a class that implements Runnable and override the run()
method. Inside the run() method, you will use Thread.sleep(500) to suspend the thread for 500
milliseconds.
2. Create a Thread Object: In the main method or another part of your program, instantiate the Runnable
class and pass it to a Thread object.
3. Start the Thread: Use the start() method of the Thread object to begin the execution of the thread.
Explanation:
1. MyRunnable Class: Implements the Runnable interface and overrides the run() method. Inside
run(), Thread.sleep(500) pauses the thread for 500 milliseconds.
2. ThreadExample Class: Creates three Thread objects, each associated with a Runnable instance
(myRunnable). The start() method is called on each Thread to begin execution, which will execute
the run() method of the Runnable interface.
This approach demonstrates how to create and start threads using the Runnable interface in Java, and how to
suspend the execution of a thread for a specific amount of time using Thread.sleep().
Object Oriented Program Programming with java
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 the main thread and created child thread are executed
concurrently.
class MyThread extends Thread {
// Constructor calling base class constructor using
super public MyThread(String threadName) {
super(threadName);
// Start the thread when the constructor is
called start();
}
// Run method to be executed when the thread
starts public void run() {
for (int i = 0; i < 5; i++)
{ System.out.println(Thread.currentThread().getName() + ": Count
" + i); try {
// Sleep for 500
milliseconds
Thread.sleep(500);
} catch (InterruptedException e)
{ System.out.println(Thread.currentThread().getName() + "
interrupted.");
}
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
}
public class MyThreadExample {
public static void main(String[] args) {
// Main thread execution
System.out.println("Main thread
started.");
Output :
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:
1. Operating System
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.
3. Eclipse IDE
● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).
● Graphics: The system should support a display with at least 1024x768 resolution.
Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Algorithm:
To create a class MyThread that extends the Thread class in Python, uses super() to call the base class
constructor, and starts the thread, you can follow these steps:
1. Create a class MyThread that inherits from Thread.
2. Define the __init__ method and call the parent class constructor using super().
3. Override the run method where the code for the child thread will be executed.
4. Start the thread by calling the start method in the constructor.
Explanation:
1. MyThread class: Inherits from threading.Thread and overrides the __init__ and run methods.
● The __init__ method uses super().__init__() to initialize the parent class (Thread),
allowing you to start the thread later.
● The run method contains the logic that the thread will execute when started. It prints messages in a
loop with a delay.
2. thread1.start() and thread2.start(): This starts the threads, which triggers the run method of
each thread to execute concurrently with the main thread.
3. join(): The join() method ensures that the main thread waits for both child threads to complete before
exiting the program.
Output:
The program will output messages from both the main thread and the child threads running concurrently. The exact
order of the output may vary each time you run the program due to the concurrent execution of threads.
Finally block executed
Object Oriented Program Programming with java
Appendix
CREATE PROJECT:
Object Oriented Program Programming with java
A Eclipse tools
A new project is created and displayed as a folder. Open the com.vogella.eclipse.ide.first folder and explore the content of
this folder.
In this tutorial the project is typically named the same as the top-level Java
package in the project. This makes is easier to find a project related to a piece of
code.
Create package
A good naming convention is to use the same name for the top level package and the
project. For example, if you name your project com.example.javaproject you should also
use com.example.javaproject as the top-level package name.
Create the com.vogella.eclipse.ide.first package by seleting the src folder, right-click on it and select New Package.
Enter MyFirstClass as the class name and select the public static void main (String[] args) checkbox.
package com.vogella.eclipse.ide.first;
You could also directly create new packages via this dialog. If you enter a new package in this dialog, it is created automatically.
Eclipse will run your Java program. You should see the output in the Console view.
Congratulations! You created your first Java project, a package, a Java class and you ran this program inside Eclipse.
Object Oriented Program Programming with java
Appendix B
Program 1
Declare a program to initialize, then that variable will be reinitialized each time the block in which
it is declared is entered.
// Demonstrate lifetime of a
variable. class LifeTime {
public static void main(String
args[]) { int x; for(x = 0; x < 3; x+
+) {
int y = -1; // y is initialized each time block is
entered System.out.println("y is: " + y); // this
always prints -1 y = 100;
System.out.println("y is now: " + y);
}
}
}
Program2
Demonstrate program demonstrates some type conversions that require casts:
// Demonstrate
casts. class
Conversion {
public static void main(String
args[]) { byte b;
int i = 257;
double d = 323.142; System.out.println("\
nConversion of int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to
int."); i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to
byte."); b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Object Oriented Program Programming with java
Conversion of int to
byte. i and b 257 1
Conversion of double to
int. d and i 323.142 323
Conversion of double to
byte. d and b 323.142 67
Program3
Demonstrate program numbers each element in the array from left to right, top to bottom, and then displays
these values:
// Demonstrate a two-dimensional
array. class TwoDArray {
public static void main(String
args[]) { int twoD[][]= new int[4]
[5];
int i, j, k = 0;
for(i=0; i<4;
i++) for(j=0;
j<5; j++)
{ twoD[i][j] =
k; k++;
for(i=0; i<4;
i++) { for(j=0;
j<5; j++)
System.out.print(twoD[i][j] +
" "); System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
Program4
Demonstrate a sample program that shows several op= assignments in action:
// Demonstrate several assignment
operators. class OpEquals {
public static void main(String
args[]) { int a = 1;
int b
= 2;
int c
= 3;
a +=
5;
b *= 4;
c += a
* b; c
%= 6;
System.out.println("a = "
Object Oriented Program Programming with java
+ a);
System.out.println("b = "
+ b);
System.out.println("c = "
+ c);
Object Oriented Program Programming with java
}
}
The output of this program is shown here:
a=6
b=8
c=3
Program 5
Demonstrate a program that uses an if-else-if ladder to determine which season a particular
month is in.
// Demonstrate if-else-if
statements. class IfElse {
public static void main(String
args[]) { int month = 4; // April
String season;
if(month == 12 || month == 1 || month
== 2) season = "Winter";
else if(month == 3 || month == 4 || month
== 5) season = "Spring";
else if(month == 6 || month == 7 || month
== 8) season = "Summer";
else if(month == 9 || month == 10 || month
== 11) season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
1. What is OOPs?
It is a programming paradigm that is used to develop software applications by creating objects that interact with
each other.
The first method takes two integers as arguments and returns their sum, while the second method takes two
doubles as arguments and returns their sum.
When we call the “add” method with two integers, the first method is called, and when we call the “add”
method with two doubles, the second method is called.
Object Oriented Program Programming with java
10. What is method overriding? Explain with an example.
It is a form of dynamic polymorphism that allows a subclass to provide its own implementation of a method
that is already defined in its superclass
For example, consider a class hierarchy that includes a superclass called “Animal” and a subclass called “Dog”.
The Animal class may have a method called “speak” that returns a string, while the Dog subclass may override
the “speak” method to return “woof”. When we call the “speak” method on a Dog object, the overridden
method in the Dog class is called, and when we call the “speak” method on an Animal object, the original
method in the Animal class is called.
a) Default constructor
This constructor is provided by Java if a class does not have any constructors explicitly defined. It takes no
parameters and initializes all the data members to their default values (e.g., null for object references, 0 for
integers, etc.).
b) Parameterized constructor
This constructor is defined by the programmer and takes one or more parameters. It initializes the data members
with the values passed as arguments.
When an object is created, it has its own unique set of properties and methods based on the definition of its
class. These properties and methods can be accessed and manipulated through the object’s public interface,
which consists of its public methods and properties.
The idea behind encapsulation is to protect the internal state of an object from being modified directly by
external code, and to enforce the use of the public interface for any interactions with the object. This helps to
prevent errors and ensure that the object is used correctly.
For example, consider a class called “Math” that contains two overloaded methods called “add”.
The first method takes two integers as arguments and returns their sum, while the second method takes two
doubles as arguments and returns their sum.
When we call the “add” method with two integers, the first method is called, and when we call the “add”
method with two doubles, the second method is called.
For example, consider a class hierarchy that includes a superclass called “Animal” and a subclass called “Dog”.
The Animal class may have a method called “speak” that returns a string, while the Dog subclass may override
the “speak” method to return “woof”.
When we call the “speak” method on a Dog object, the overridden method in the Dog class is called, and when
we call the “speak” method on an Animal object, the original method in the Animal class is called.
In Java, a constructor has the same name as the class and does not have a return type, not even void. It is called
implicitly when an object is created using the “new” keyword, and it can also be called explicitly like any other
method.
b) Parameterized constructor
This constructor is defined by the programmer and takes one or more parameters. It initializes the data members
with the values passed as arguments.
26. What is the difference between an instance variable and a class variable?
In object-oriented programming, instance variables and class variables are two types of variables that can be
declared within a class. The main difference between them is that instance variables are associated with an
instance of a class, while class variables are associated with the class itself.
● Encapsulation
● Inheritance
● Polymorphism
● Abstractio