0% found this document useful (0 votes)
13 views37 pages

Java Class Assignments Overview

The document outlines various Java class implementations, including BankAccount, Student, Rectangle, Book, Vehicle, and Person, each with specific attributes and methods. It demonstrates object creation, method usage, and output for each class, showcasing functionalities like deposit/withdraw for bank accounts, grade calculation for students, area/perimeter calculations for rectangles, and book comparisons. Additionally, it includes a library catalog and shape representation, highlighting the versatility of Java in object-oriented programming.

Uploaded by

baditya985
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)
13 views37 pages

Java Class Assignments Overview

The document outlines various Java class implementations, including BankAccount, Student, Rectangle, Book, Vehicle, and Person, each with specific attributes and methods. It demonstrates object creation, method usage, and output for each class, showcasing functionalities like deposit/withdraw for bank accounts, grade calculation for students, area/perimeter calculations for rectangles, and book comparisons. Additionally, it includes a library catalog and shape representation, highlighting the versatility of Java in object-oriented programming.

Uploaded by

baditya985
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

ASSIGNMENT-JAVA BALA ADTYA J

22AD014

CLASS
1. Define a Java class named BankAccount that represents a simple bank account.
The class should have
instance variables for account number, account holder's name, and account
balance. Include methods to
deposit and withdraw funds, and a method to display the account details.

public class BankAccount {


// Instance variables
private int accountNumber;
private String accountHolderName;
private double accountBalance;

// Constructor
public BankAccount(int accountNumber, String accountHolderName, double
initialBalance) {
[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = initialBalance;
}

// Method to deposit funds


public void deposit(double amount) {
if (amount > 0) {
accountBalance += amount;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link](amount + " deposited. New balance: " +
accountBalance);
} else {
[Link]("Invalid amount for deposit.");
}
}

// Method to withdraw funds


public void withdraw(double amount) {
if (amount > 0 && amount <= accountBalance) {
accountBalance -= amount;
[Link](amount + " withdrawn. New balance: " +
accountBalance);
} else {
[Link]("Insufficient funds or invalid amount for withdrawal.");
}
}

// Method to display account details


public void displayAccountDetails() {
[Link]("Account Number: " + accountNumber);
[Link]("Account Holder: " + accountHolderName);
[Link]("Account Balance: " + accountBalance);
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public static void main(String[] args) {
// Creating an instance of BankAccount
BankAccount account = new BankAccount(123456, "John Doe", 1000.0);

// Depositing and withdrawing funds


[Link](500.0);
[Link](200.0);

// Displaying account details


[Link]();
}
}
Output:
500.0 deposited. New balance: 1500.0
200.0 withdrawn. New balance: 1300.0
Account Number: 123456
Account Holder: John Doe
Account Balance: 1300.0

2. Create a Java class called Student to represent a student's information. Include


attributes such as name,
age, grade, and a constructor to initialize these values. Implement a method that
calculates and returns
the student's grade based on a predefined grading scale.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

public class Student {


// Instance variables
private String name;
private int age;
private double grade;

// Constructor
public Student(String name, int age, double grade) {
[Link] = name;
[Link] = age;
[Link] = grade;
}

// Method to calculate and return the student's grade


public String calculateGrade() {
if (grade >= 90) {
return "A";
} else if (grade >= 80) {
return "B";
} else if (grade >= 70) {
return "C";
} else if (grade >= 60) {
return "D";
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
} else {
return "F";
}
}

public static void main(String[] args) {


// Creating an instance of Student
Student student = new Student("Alice", 18, 85.5);

// Calculating and displaying the student's grade


String studentGrade = [Link]();
[Link]([Link]() + "'s grade: " + studentGrade);
}

// Getter for name


public String getName() {
return name;
}
}

Output:
Name: Alice
Age: 18
Grade: 87.5
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Calculated Grade: B

3. Define a Java class named Rectangle that models a rectangle shape. Include
attributes for width and
height, and provide methods to calculate the area and perimeter of the rectangle.
Create multiple
instances of the class and demonstrate the usage of these methods.

public class Rectangle {


// Instance variables
private double width;
private double height;

// Constructor
public Rectangle(double width, double height) {
[Link] = width;
[Link] = height;
}

// Method to calculate the area of the rectangle


public double calculateArea() {
return width * height;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
}

// Method to calculate the perimeter of the rectangle


public double calculatePerimeter() {
return 2 * (width + height);
}

public static void main(String[] args) {


// Creating instances of Rectangle
Rectangle rectangle1 = new Rectangle(5.0, 10.0);
Rectangle rectangle2 = new Rectangle(3.0, 7.0);

// Calculating and displaying area and perimeter for rectangle1


[Link]("Rectangle 1:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
[Link]();

// Calculating and displaying area and perimeter for rectangle2


[Link]("Rectangle 2:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

Output:
Rectangle 1:
Area: 50.0
Perimeter: 30.0

Rectangle 2:
Area: 21.0
Perimeter: 20.0

4. Implement a Java class called Book to represent a book's details, including title,
author, year of
publication, and ISBN number. Create methods to display these details and
compare two books based
on their publication years.

public class Book {


// Instance variables
private String title;
private String author;
private int yearOfPublication;
private String isbn;

// Constructor
public Book(String title, String author, int yearOfPublication, String isbn) {
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link] = title;
[Link] = author;
[Link] = yearOfPublication;
[Link] = isbn;
}

// Method to display book details


public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Year of Publication: " + yearOfPublication);
[Link]("ISBN: " + isbn);
}

// Method to compare two books based on publication years


public int compareByPublicationYear(Book otherBook) {
return [Link]([Link], [Link]);
}

public static void main(String[] args) {


// Creating instances of Book
Book book1 = new Book("To Kill a Mockingbird", "Harper Lee", 1960, "978-0-
06-112008-4");
Book book2 = new Book("1984", "George Orwell", 1949, "978-0-452-28423-
4");
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying details for each book


[Link]("Book 1:");
[Link]();
[Link]();

[Link]("Book 2:");
[Link]();
[Link]();

// Comparing books based on publication years


int comparison = [Link](book2);
if (comparison > 0) {
[Link]("Book 1 was published after Book 2.");
} else if (comparison < 0) {
[Link]("Book 1 was published before Book 2.");
} else {
[Link]("Both books were published in the same year.");
}
}
}

Output:
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Book 1:
Title: To Kill a Mockingbird
Author: Harper Lee
Year of Publication: 1960
ISBN: 978-0-06-112008-4

Book 2:
Title: 1984
Author: George Orwell
Year of Publication: 1949
ISBN: 978-0-452-28423-4

Book 1 was published after Book 2.

5. Create a base class named Vehicle with attributes like make, model, and year.
Derive a subclass Car
from Vehicle with additional attributes specific to cars, such as the number of
doors and fuel efficiency.
Include methods to display the car's details and calculate fuel consumption.
// Base class: Vehicle
class Vehicle {
// Instance variables
protected String make;
protected String model;
protected int year;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Constructor
public Vehicle(String make, String model, int year) {
[Link] = make;
[Link] = model;
[Link] = year;
}

// Method to display vehicle details


public void displayDetails() {
[Link]("Make: " + make);
[Link]("Model: " + model);
[Link]("Year: " + year);
}
}

// Subclass: Car (inherits from Vehicle)


class Car extends Vehicle {
// Additional attributes for cars
private int numDoors;
private double fuelEfficiency; // miles per gallon

// Constructor
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public Car(String make, String model, int year, int numDoors, double
fuelEfficiency) {
super(make, model, year); // Calling base class constructor
[Link] = numDoors;
[Link] = fuelEfficiency;
}

// Method to display car details


public void displayCarDetails() {
[Link](); // Calling base class method
[Link]("Number of Doors: " + numDoors);
[Link]("Fuel Efficiency: " + fuelEfficiency + " miles per gallon");
}

// Method to calculate fuel consumption


public double calculateFuelConsumption(double distance) {
return distance / fuelEfficiency;
}
}

public class Main {


public static void main(String[] args) {
// Creating an instance of Car
Car car = new Car("Toyota", "Camry", 2022, 4, 30.5);
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying car details


[Link]("Car Details:");
[Link]();
[Link]();

// Calculating fuel consumption for a distance of 200 miles


double distance = 200.0;
double fuelConsumption = [Link](distance);
[Link]("Fuel Consumption for " + distance + " miles: " +
fuelConsumption + " gallons");
}
}

Output:

Car Details:
Make: Toyota
Model: Camry
Year: 2022
Number of Doors: 4
Fuel Efficiency: 30.5 miles per gallon

Fuel Consumption for 200.0 miles: 6.557377049180328 gallons


ASSIGNMENT-JAVA BALA ADTYA J
22AD014

Object creation
1. Write a Java program to define a Person class with attributes for name, age, and
occupation. Create
objects for different people and display their information.

public class Person {


// Instance variables
private String name;
private int age;
private String occupation;

// Constructor
public Person(String name, int age, String occupation) {
[Link] = name;
[Link] = age;
[Link] = occupation;
}

// Method to display person's information


public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Occupation: " + occupation);
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link]();
}

public static void main(String[] args) {


// Creating objects for different people
Person person1 = new Person("John Doe", 30, "Engineer");
Person person2 = new Person("Jane Smith", 25, "Teacher");
Person person3 = new Person("Michael Johnson", 40, "Doctor");

// Displaying information for each person


[Link]("Person 1:");
[Link]();

[Link]("Person 2:");
[Link]();

[Link]("Person 3:");
[Link]();
}
}

Output:
Person 1:
Name: John Doe
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Age: 30
Occupation: Engineer

Person 2:
Name: Alice Smith
Age: 25
Occupation: Teacher

Person 3:
Name: Michael Johnson
Age: 45
Occupation: Doctor

3. Create a Java program for a library catalog. Define a Book class with attributes
for title, author, and
genre. Create objects for various books and display their details.

public class Book {


// Instance variables
private String title;
private String author;
private String genre;

// Constructor
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public Book(String title, String author, String genre) {
[Link] = title;
[Link] = author;
[Link] = genre;
}

// Method to display book details


public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Genre: " + genre);
}

public static void main(String[] args) {


// Creating objects for various books
Book book1 = new Book("To Kill a Mockingbird", "Harper Lee", "Fiction");
Book book2 = new Book("1984", "George Orwell", "Dystopian");
Book book3 = new Book("Pride and Prejudice", "Jane Austen", "Romance");

// Displaying details for each book


[Link]("Book 1:");
[Link]();
[Link]();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link]("Book 2:");
[Link]();
[Link]();

[Link]("Book 3:");
[Link]();
}
}

Output:
Book 1:
Title: To Kill a Mockingbird
Author: Harper Lee
Genre: Fiction

Book 2:
Title: 1984
Author: George Orwell
Genre: Dystopian

Book 3:
Title: Pride and Prejudice
Author: Jane Austen
Genre: Romance
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

4. Implement a Java program to represent basic shapes. Define a Shape class with
attributes for type (e.g.,
circle, triangle) and properties related to that shape (e.g., radius, side lengths).
Create objects for
different shapes and calculate/display relevant properties.

public class Shape {


// Instance variables
private String type;
private double[] properties;

// Constructor
public Shape(String type, double... properties) {
[Link] = type;
[Link] = properties;
}

// Method to calculate area for different shapes


public double calculateArea() {
if ([Link]("circle")) {
return [Link] * properties[0] * properties[0]; // properties[0] is radius
} else if ([Link]("triangle")) {
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
double s = (properties[0] + properties[1] + properties[2]) / 2; //
semiperimeter
return [Link](s * (s - properties[0]) * (s - properties[1]) * (s -
properties[2]));
} else {
return -1; // Invalid shape
}
}

// Method to display shape details


public void displayDetails() {
[Link]("Shape type: " + type);
for (int i = 0; i < [Link]; i++) {
[Link]("Property " + (i + 1) + ": " + properties[i]);
}
[Link]("Area: " + calculateArea());
}

public static void main(String[] args) {


// Creating objects for different shapes
Shape circle = new Shape("circle", 5.0); // Radius = 5.0
Shape triangle = new Shape("triangle", 3.0, 4.0, 5.0); // Side lengths = 3.0, 4.0,
5.0

// Displaying details for each shape


ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link]("Circle:");
[Link]();
[Link]();

[Link]("Triangle:");
[Link]();
}
}

Output:
Circle:
Shape type: circle
Property 1: 5.0
Area: 78.53981633974483

Triangle:
Shape type: triangle
Property 1: 3.0
Property 2: 4.0
Property 3: 5.0
Area: 6.0
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
5. Write a Java program to manage employee records. Define an Employee class
with attributes for name,
role, and salary. Create objects for employees and implement methods to update
salary and display their
information.

public class Employee {


// Instance variables
private String name;
private String role;
private double salary;

// Constructor
public Employee(String name, String role, double salary) {
[Link] = name;
[Link] = role;
[Link] = salary;
}

// Method to update the salary


public void updateSalary(double newSalary) {
salary = newSalary;
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Method to display employee information
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Role: " + role);
[Link]("Salary: " + salary);
}

public static void main(String[] args) {


// Creating employee objects
Employee employee1 = new Employee("John Doe", "Manager",
50000.0);
Employee employee2 = new Employee("Alice Smith", "Developer",
60000.0);

// Displaying information for each employee


[Link]("Employee 1:");
[Link]();
[Link]();

[Link]("Employee 2:");
[Link]();
[Link]();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Updating salary for employee 1


[Link](55000.0);

// Displaying updated information for employee 1


[Link]("Updated Employee 1:");
[Link]();
}
}

Output:
Employee 1:
Name: John Doe
Role: Manager
Salary: 50000.0

Employee 2:
Name: Alice Smith
Role: Developer
Salary: 60000.0

Updated Employee 1:
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Name: John Doe
Role: Manager
Salary: 55000.0

Default Constructor:
1. Create a Java program to define a class BankAccount with instance variables for
account number and
balance. Implement a default constructor that initializes the account number to a
default value and
balance to 0. Display the account details after initialization.

public class BankAccount {


// Instance variables
private int accountNumber;
private double balance;

// Default constructor
public BankAccount() {
accountNumber = 123456; // Default account number
balance = 0.0; // Default balance
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Method to display account details
public void displayAccountDetails() {
[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}

public static void main(String[] args) {


// Creating an instance of BankAccount using the default constructor
BankAccount account = new BankAccount();

// Displaying account details after initialization


[Link]();
}
}
OUTPUT:
Account Number: 123456
Balance: 0.0

2. Write a Java program that defines a class Student with instance variables for
name, age, and student ID.
Use a default constructor to initialize the student's information with default
values. Print the student's
details after initialization.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public class Student {
// Instance variables
private String name;
private int age;
private int studentID;

// Default constructor
public Student() {
name = "John Doe"; // Default name
age = 18; // Default age
studentID = 123456; // Default student ID
}

// Method to display student details


public void displayStudentDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Student ID: " + studentID);
}

public static void main(String[] args) {


// Creating an instance of Student using the default constructor
Student student = new Student();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Displaying student details after initialization
[Link]();
}
}

Output: Name: John Doe


Age: 18
Student ID: 123456

3. Design a Java class Calculator with variables for two numbers and a result.
Create a default constructor
that sets the numbers to default values and initializes the result. Implement
methods for addition,
subtraction, multiplication, and division. Display the calculated results.

public class Calculator {


// Instance variables
private double num1;
private double num2;
private double result;

// Default constructor
public Calculator() {
num1 = 0.0; // Default value
num2 = 0.0; // Default value
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
result = 0.0; // Initialized result
}

// Method for addition


public void add() {
result = num1 + num2;
}

// Method for subtraction


public void subtract() {
result = num1 - num2;
}

// Method for multiplication


public void multiply() {
result = num1 * num2;
}

// Method for division


public void divide() {
if (num2 != 0) {
result = num1 / num2;
} else {
[Link]("Cannot divide by zero.");
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
}
}

// Method to display the result


public void displayResult() {
[Link]("Result: " + result);
}

public static void main(String[] args) {


// Creating an instance of Calculator
Calculator calculator = new Calculator();

// Performing calculations and displaying results


[Link]();
[Link]("Addition: ");
[Link]();

[Link]();
[Link]("Subtraction: ");
[Link]();

calculator.num1 = 10;
calculator.num2 = 5;
[Link]();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
[Link]("Multiplication: ");
[Link]();

[Link]();
[Link]("Division: ");
[Link]();
}
}

Output:
Addition: Result: 0.0
Subtraction: Result: 0.0
Multiplication: Result: 50.0
Division: Result: 2.0

4. Develop a Java class Person with attributes for name, age, and gender. Include a
default constructor that
sets default valuesfor these attributes. Create instances of the class and print out
the details of the person
objects.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public class Person {
// Instance variables
private String name;
private int age;
private String gender;

// Default constructor
public Person() {
name = "Unknown"; // Default name
age = 0; // Default age
gender = "Unknown"; // Default gender
}

// Method to display person details


public void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Gender: " + gender);
}

public static void main(String[] args) {


// Creating instances of Person using the default constructor
Person person1 = new Person();
Person person2 = new Person();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying person details for each instance


[Link]("Person 1:");
[Link]();
[Link]();

[Link]("Person 2:");
[Link]();
}
}

Output:
Person 1:
Name: Unknown
Age: 0
Gender: Unknown

Person 2:
Name: Unknown
Age: 0
Gender: Unknown
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
5. Build a Java class Vehicle with instance variables for make, model, and year.
Define a default
constructor that initializes the vehicle details to default values. Create objects of
the class and display
the vehicle information.

public class Vehicle {


// Instance variables
private String make;
private String model;
private int year;

// Default constructor
public Vehicle() {
make = "Unknown"; // Default make
model = "Unknown"; // Default model
year = 0; // Default year
}

// Method to display vehicle information


public void displayInfo() {
[Link]("Make: " + make);
[Link]("Model: " + model);
[Link]("Year: " + year);
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

public static void main(String[] args) {


// Creating instances of Vehicle using the default constructor
Vehicle vehicle1 = new Vehicle();
Vehicle vehicle2 = new Vehicle();

// Displaying vehicle information for each instance


[Link]("Vehicle 1:");
[Link]();
[Link]();

[Link]("Vehicle 2:");
[Link]();
}
}

Output:
Vehicle 1:
Make: Unknown
Model: Unknown
Year: 0

Vehicle 2:
Make: Unknown
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Model: Unknown
Year: 0

Common questions

Powered by AI

Challenges in implementing methods within the `Employee` class include maintaining data consistency and ensuring accuracy when updating salary information. For example, the `updateSalary` method directly modifies the salary attribute, which requires careful input validation to avoid assigning nonsensical values (e.g., negative salaries). Additionally, the `displayInfo` method must correctly reflect the most recent values stored in the object's attributes. These challenges are resolved by strict method design, where outer interactions with sensitive data are encapsulated, logical checks are conducted before modifying attributes, and separation of concerns ensures consistent object state visibility .

A Java class representing a bank account, such as 'BankAccount', typically includes instance variables for the account number, account holder's name, and account balance. These variables store the fundamental details of a bank account. The class should also implement methods to deposit and withdraw funds, checking if the operation is valid (e.g., using conditions to ensure positive deposit amounts and sufficient balance for withdrawals). Furthermore, a method to display account details is essential for providing a summary of the account information. These components interact by enabling the creation of account instances, manipulation of account balance through deposits and withdrawals, and presentation of account data through the display method .

Default constructors in classes like `BankAccount` and `Student` automatically initialize object instances with predefined default values when no specific initialization is requested. For instance, the `BankAccount` constructor sets a default account number and balance of 0, while the `Student` constructor assigns a default name, age, and student ID. These default settings simplify object creation by ensuring objects are initialized with basic, valid state conditions without requiring explicit parameter input, thus supporting code reusability and reducing error potential during instantiation .

A `Person` class with a default constructor streamlines object creation by establishing default values for attributes such as name, age, and gender. This approach enhances flexibility by allowing for the instantiation of objects with minimal configuration, enabling rapid prototyping and scenario testing where precise details are initially irrelevant. It supports use cases where default data suffices or provides a baseline upon which specific contexts can customize object details later, thus promoting application adaptability and reducing the overhead associated with frequent explicit detail assignments .

The `Student` class calculates a student's grade using a method `calculateGrade`, which applies conditional logic to determine the letter grade based on the student's numeric grade. The logic follows a predefined scale: grades above or equal to 90 receive an 'A', 80 to 89 a 'B', 70 to 79 a 'C', 60 to 69 a 'D', and below 60 an 'F'. Such conditional statements evaluate the numeric grade and return the corresponding letter grade, encapsulating the grading policy within the class to consistently assign grades based on standardized criteria .

Designing a `Shape` class to handle different geometric forms involves flexibility and abstraction. The class should include attributes that can store a variety of properties relevant to each type of shape, such as radius for circles or side lengths for triangles. Methods like `calculateArea` should determine the shape type dynamically and perform corresponding calculations. The constructor can use variable arguments to accommodate different property requirements. The class should also ensure the accuracy of operations through conditional logic that verifies input appropriateness for each shape type, allowing for dynamic behavior while maintaining robustness and efficiency .

The `Rectangle` class demonstrates encapsulation by defining private instance variables such as width and height, protecting them from direct external modification. It offers public methods to calculate the rectangle's area and perimeter, encapsulating these computations within the class and enhancing modularity. These methods utilize the encapsulated data, demonstrating how class instances can perform operations using their own attributes. As a result, the class provides a clear API for clients to calculate and retrieve geometric properties without needing to access underlying data directly .

The `Car` class extends the `Vehicle` class by inheriting its attributes like make, model, and year, which are protected and accessible to subclasses. The `Car` class adds specific attributes such as the number of doors and fuel efficiency, enhancing the functionality by incorporating car-specific data. The `Car` class also includes additional methods to display detailed car information (utilizing base class methods via `super`) and calculate fuel consumption based on the distance traveled and the car's fuel efficiency .

In the `Book` class, the `compareByPublicationYear` method compares the publication years of two book instances, using the `Integer.compare` method to return a result indicating if one book's year is greater, equal to, or less than the other. This process invokes an OOP approach to facilitate comparative decision-making within the context of book objects. Practically, this allows easy sorting and organization of books based on their publication date, aiding in library management systems and providing users with historical insights into publication trends or author productivity over time .

The `Calculator` class exemplifies object-oriented principles by encapsulating variables for numbers and results, using methods to perform arithmetic operations—addition, subtraction, multiplication, and division. Each method operates on encapsulated data, modifying the result based on user input or using default values. This design segregates operations from direct access, allowing controlled interaction and preventing misuse. The class effectively manages arithmetic by checking for conditions, such as division by zero, thus safeguarding correctness. This encapsulation alongside robust handling showcases the blending of object-oriented principles with practical arithmetic management .

You might also like