SLC S22 Week2 || The Object Approach In JAVA

Hello everyone! I hope you will be good. Today I am here to participate in the contest of @kouba01 about The Object Approach In JAVA. It is really an interesting and knowledgeable contest. There is a lot to explore. If you want to join then:



Join Here: SLC S22 Week2 || The Object Approach In JAVA




Designed with Canva

Task1

Which of the following statements about Java classes and objects is true?

Answers:

  1. What is a class in Java?
    (A) A blueprint for creating objects.
    Explanation: A class in Java defines the structure and behavior that objects of that class will have. It serves as a template or blueprint for creating objects.

  2. What does the new keyword do in Java?
    (B) Creates a new object of a class.
    Explanation: The new keyword is used to allocate memory and instantiate an object of a specified class.

  3. Which of the following statements is true about attributes in a class?
    (C) Attributes store data for an object.
    Explanation: Attributes, also known as fields or properties, are variables that hold data specific to an object.

  4. What is the purpose of a constructor in a class?
    (B) To initialize the fields of a class.
    Explanation: Constructors are special methods used to initialize the fields of an object when it is created.



Task2

Write a program that demonstrates the creation and use of a class by including attributes, methods, and object instantiation. Specifically, create a Laptop class with attributes brand (a string) and price (a double).

image.png
image.png

Explanation:

1. Class Definition (Laptop)

Attributes:

I have declared two attributes of the class which are given below:

  • brand: A String that holds the brand of the laptop.
  • price: A double that holds the price of the laptop.

These attributes are declared as private to abide by the principle of encapsulation which prevents them from being accessed directly from outside the class.

Constructor:

  • According to the requirement of the task I have then created a constructor named Laptop./ This will initialize the attributes at the time of creation of any object of the class.
  • It accepts two parameters brand and price. These are used to assign values to the attributes of the object that is being created.

Method (displayDetails):

  • This is a public method that prints the laptop details such as its brand and price.
  • System.out.println is used to format and print the output.

2. Main Class (Main)

  • The Main class has the main method which is the entry point of the program.

Object Creation:

There are two objects of the Laptop class created using the new keyword:

  • laptop1 is assigned with brand "Dell" and price 899.99.
  • laptop2 is assigned with brand "HP" and price 749.50.
    The constructor of the Laptop class is called for each object and it is passing the respective values as arguments.

Calling Methods:

  • The displayDetails method is called on each object laptop1 and laptop2 to print their respective details for the user.
  • The output is formatted using headers such as "Laptop 1 Details:" and "Laptop 2 Details:" in order to keep the data separate for each object clearly.

3. Program Flow

  1. The class Laptop has attributes, a constructor and a method.
  2. In the Main class:
    • Two Laptop objects are initiated with different values.
    • The displayDetails method is called for each object and the details are printed to the console.
  3. The program terminates after displaying the details of both objects.

Important Features

  1. Encapsulation: The private keyword ensures that the attributes of the class can only be accessed via methods.
  2. Reusability: The Laptop class is reusable, and multiple objects with different values can be created easily.
  3. Object-Oriented Programming: This example illustrates the basic concepts of OOP:
    • Class and Object creation.
    • Using a constructor for initialization.
    • Encapsulation with attributes and methods.

This program is a simple but effective demonstration of how to create and use a class in Java.



Task3

Write a program that demonstrates the creation of a Movie class, its attributes, and methods, along with managing multiple objects in an array. Define the Movie class with the attributes title (a string) and rating (a double).

Here is the program that demonstrates the creation of a Movie class, its attributes, and methods, while managing multiple objects in an array.

image.png
image.png

Explanation

1. Class Definition (Movie)

Attributes:

Here in this class I have declared two attributes as follows:

  • title: A String that holds the title of the movie.
  • rating: A double that holds the rating of the movie on a scale of 10.
  • Both attributes are declared private to ensure encapsulation.

Constructor:

  • The Movie constructor takes arguments to assign values to the title and rating properties when a Movie object is created.

Method (displayInfo):

  • The method prints out the title and rating of a movie.
  • The rating is printed as a fraction of 10.

2. Main Method

Array Creation:

  • A new array called movies of size 3 is created to hold three objects of type Movie.

Fill the Array:

  • The array is filled with instances of the Movie class by using the new keyword.
  • Every object is initialized with some specific values for title and rating.

**Print the Details:

  • A for-each loop iterates through the movies array and calls the displayInfo method for each Movie object to print its information.
  • The details of each movie are printed on a new line for better readability.

Important Features

  1. Encapsulation: The Movie class employs private attributes and public methods to control and modify access.
  2. Array of Objects: The program illustrates the management of a set of objects of a class using an array.
  3. Constructor Usage: An array of objects is instantiated using a parameterized constructor to make the program easy and readable.
  4. Iteration with Loops: The for-each loop simplifies accessing each object in the array.

This program explains how to manage multiple objects of a class and structure their data for efficiency and reusability.



Task4

Write a program that demonstrates adding methods with calculations by creating a Product class. The class should include the attributes name (a string), price (a double), and quantity (an integer).

image.png
image.png

Explanation

1. Class Definition (Product)

Attributes:

I have declared 3 attributes in the class product which are as follows:

  • name: A String that holds the name of the product.
  • price: A double that represents the price of one unit of the product.
  • quantity: An int that holds the quantity of the product.
  • These attributes are private for encapsulation.

Constructor:

Then there is a constructor to initialize the attributes with values at the time of creation of a Product object.

Method (calculateTotalPrice):

  • This is the method to calculate the total price so its presence compute the total price of the product by multiplying price with the quantity of the product.
  • After the calculation this method return the computed value as a double.

Method (displayProduct):

  • Display the details of the product including its name, price per unit, quantity and total price.
  • Calls the calculateTotalPrice method to calculate and print the total price dynamically.

2. Main Method

Object Creation:

  • An object of the Product class is created using the new keyword which is then initialized with specific values for name, price and quantity.

Calling Methods:
The displayProduct method is called to print all details of the product including the calculated total price.

Key Features

  1. Encapsulation: The Product class holds all its attributes in private and has methods for accessing it.
  2. Dynamic Calculation: The calculateTotalPrice method ensures the total price is calculated dynamically by current values.
  3. Reusability: The displayProduct method centralizes the display logic to be reused with multiple product objects.
  4. Real World Simulation: This program simulates the real-world concept of inventory management by merging product information with calculations.


Task5

Write a program that manages student records by creating a Student class. The class should have the attributes id (an integer), name (a string), and marks (an array of integers).


image.png
image.png

Explanation

1. Class Definition (Student):

The Student class encapsulates all details and functionality about a student in an attempt to embody the principles of Object Oriented Programming, namely encapsulation and modularity.

Attributes:

I have declared three attributes of the class Student which are given below:

  • id: An integer uniquely identifying each student.
  • name: A string for the student's name.
  • marks: An array of integers to store the marks obtained by the student in different subjects.
  • These are private, thus data is accessible only through class methods.

Constructor:

  • A constructor initializes the attributes when a Student object is created.
  • The students[0] sets id to 1, name to "Ali", and marks to {85, 90, 78} in the first student object

Method calculateAverage():

The calculateAverage method calculates the average marks of the student:

  1. Loop Through Marks: Iterates through the marks array and calculates the total sum.
  2. Average Calculation: The sum is divided by the number of subjects, which is marks.length to obtain the average.
  3. Handling Precision: It returns a double value in order to handle the decimal values and therefore to produce the accurate result of the averages.

Method displayDetails():

This method prints all the details of a student, including their:

- `id` (Student ID).
- `name` (Student's name).
- `marks` (All marks as a list).
- `average marks` (Calculated using the `calculateAverage` method).
  • It uses a for-each loop to display all marks ensuring readability.

2. Main Method:

The main method is the entry point of the program and demonstrates how the Student class is used in a real-world scenario.

Array of Student Objects:

  • The program utilizes an array to hold several Student objects. An array makes sure all students are stored and retrieved in an efficient manner.
  • Every element of the array is initialized with a Student object. Thus unique values are given to id, name and marks.

Filling the Array:

  • The array is filled with an explicit call to the Student constructor with appropriate parameters:

Displaying Details:

  • A for-each loop is used to iterate through the Student array, calling the displayDetails method for each Student object.
  • This does guarantee the details of all the students are printed out in sequence, so that code will be scalable and easily extensible.

3. Key Features

Dynamically Computed:

  • The program computes the average marks dynamically, using the calculateAverage method. This is an example of clean separation of concerns because each method deals with one specific task.

Encapsulation:

  • The private attributes and public methods make sure that the internal data of the Student class is properly protected and accessed only via class methods.

Reusability:

  • Methods such as calculateAverage and displayDetails make the code modular, reusable, and easy to maintain.

Handling Multiple Objects:

  • This is an example of using an array to manage multiple objects of type Student. It shows how OOP concepts work effectively for managing real-world entities.

Readability and Structure:

  • It utilizes clean loops, correct method calls, and good output formatting to make the program legible and easy to read.

image.png

  • Student Information: The first student "Ali" has her id, name, and marks printed out
  • Average Marks: This program dynamically calculates and prints out Alice's average marks (84.33).
  • This cycle goes for the three students, so all records are handled without difficulties.

The program is clear, scalable and maintainable by organizing and managing the student data using OOP concepts while giving accurate results.



Task6

Write a program to simulate a simple Library Management System.

Here is the implementation of a simple Library Management System in Java:

This program implements a Library Management System with two main classes: Book and Library. The system makes use of a menu driven approach so that it interacts with the user and allows to manage books within the library effectively.

Class Overview

1. Book Class:

The class represents a single book in the library. This class encapsulates the attributes and methods related to the individual book operations.

Attributes:

In the Book class I have declared these four attributes:

  • id (int): An ID number to identify a book. For example, when a user wants to borrow or return a book.
  • title (String): Title of the book.
  • author (String): Name of the author of the book.
  • isAvailable (boolean): Checks if the book is available for borrowing, or is currently borrowed. It can be true or false.

Methods:

  1. Constructor:
    • Initializes the book's attributes (id, title, author) and sets isAvailable to true by default, indicating the book is initially available.
  2. borrowBook():
    • Checks if the book is available:
    • If available, updates isAvailable to false and confirms the borrow operation.
    • If not available, he then lets the user know that this book can't be borrowed.
  3. returnBook():
    • Sets the variable isAvailable to true marking that the book is in the library.
  4. displayDetails():
    • Outputs information related to the book about itself in a clean form along with its availability ("Yes" or "No").
  5. Accessors (e.g., getId(), getTitle():
    • Provide controlled access to specific attributes.

2. Library Class:

This class is the library as a whole and encapsulates the operations to be performed.

Attributes:
This class has the following attributes:

  • books (ArrayList < Book >): This is a dynamic collection of Book objects stored in an ArrayList. This kind of data structure allows books to be easily added, removed, and traversed.

Methods:

  1. addBook(Book book):
    • Adds a new book to the library's collection and confirms the addition.
  2. displayAllBooks():
    • It iterates through the books list and displays the details of each book using their displayDetails() method.
    • If the library has no books, it notifies the user.
  3. searchByTitle(String title):
    • Searches the library for a book with a matching title (case-insensitive).
    • If found displays the book's details using displayDetails().
    • If not found informs the user.
  4. borrowBook(int id):
    • Finds a book with the ID given.
    • Calls its borrowBook() method if found.
    • If not available it prompts the user.
  5. returnBook(int id):
    • Finds a book with the ID.
    • If found calls its method returnBook().
    • If not found then prompts the user.

3. Main Method:

This is the entry point of the program where the library system is initialized and user interactions take place.

Initialization:

  • A Library object is created and three initial books are added using the addBook() method.

Menu-Driven Interface:

  • A menu with five options is presented:
    1. View all books.
    2. Search for a book by title.
    3. Borrow a book by ID.
    4. Return a book by ID.
    5. Exit the program.
  • The user selects an option, and the program performs the corresponding operation by invoking the appropriate Library methods.

User Interaction:

  • Input is taken using a Scanner object.
  • The program deals with valid and invalid inputs gracefully by giving error messages or instructions.

Key Features and Highlights:

  1. Object-Oriented Design:

    • The program follows the principles of OOP by encapsulating data and behaviour in the Book and Library classes.
    • Modular design ensures easy maintainability and extensibility.
  2. Dynamic Collection:

    • The use of ArrayList allows the library to manage a flexible number of books without predefined size constraints.
  3. Interactivity:

    • The menu-driven interface enhances usability by guiding the user through various library operations.
  4. Error Handling:

    • For example, borrowing or returning a non-existent book (invalid ID) triggers appropriate error messages.
  5. Reusability:

  • Methods such as displayDetails(), borrowBook(), and returnBook() in the Book class are reused by the Library class. This encourages code reuse.

Execution Walkthrough Example:

Step 1: Initial Setup

The program begins with three books in the library:

  • Book 1: 1984 by George Orwell
  • Book 2: To Kill a Mockingbird by Harper Lee
  • Book 3: The Great Gatsby by F. Scott Fitzgerald

Step 2: User Options

  1. View All Books

    • It shows the details of all books along with its availability status.
  2. Search for a Book by Title

    • Whenever the user searches for a title, say 1984, the program would display its details.
    • If the user does a search for a nonexistent title, the program will then inform the user.
  3. Borrow a Book by ID

    • If the user inputs ID 1, the program indicates that 1984 is borrowed.
    • If the book is already borrowed, it will inform the user.
  4. Return a Book by ID

    • If the user returns a borrowed book, for example, ID 1, the program marks it as available.
    • In case the book was not borrowed or the ID does not exist, it informs the user.
  5. Exit

    • Stops the program cleanly.


I would like to invite @heriadi, @chant and @jospeha to join this contest.



Sort:  
Loading...

Coin Marketplace

STEEM 0.24
TRX 0.27
JST 0.040
BTC 96948.35
ETH 3468.05
SBD 1.56