SLC S22 Week2 || The Object Approach In JAVA

Assalamualaikum my fellows I hope you will be fine by the grace of Allah. Today I am going to participate in the steemit learning challenge season 22 week 2 by @kouba01 under the umbrella of steemit team. It is about The Object Approach In JAVA. Let us start exploring this week's teaching course.


Green and Yellow Modern Programmer Presentation (4).png

Made with Canva

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

Here are the correct answers for each question:

1. What is a class in Java?
(A) A blueprint for creating objects.
Explanation: A class is a template or blueprint that defines the structure and behavior of objects created from it.


2. What does the new keyword do in Java?
(B) Creates a new object of a class.
Explanation: The new keyword is used to create a new instance of a class, allocating memory for the object.


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


4. What is the purpose of a constructor in a class?
(B) To initialize the fields of a class. A constructor is a special method used to initialize an object's fields when it is created.



Write a program that demonstrates the creation and use of a class by including attributes, methods, and object instantiation.

Here is the Java program which demonstrates the creation and use of the class by including attributes, methods, and object instantiation:


image.png
image.png

Here is an explanation of the program with functionality:

1. Defining the Laptop Class:

The program begins by defining a Laptop class that encapsulates the essential properties of a laptop. This class has two attributes: brand (a String) and price (a double). These attributes are used to store information about the laptop's brand and price.


image.png


2. Constructor for Initialization:

The Laptop class has a constructor to initialize its attributes. A constructor is a special method that gets called when a new object is being created. Here, this constructor takes two parameters called brand and price and assigns them to the class's fields. This would ensure that every Laptop object is always initialized with particular values.

image.png


3. Method to Display Laptop Details:

The Laptop class also declares a method, displayDetails(), to print out the details of a laptop in an easy-to-read format. The method calls print out the brand and price of a laptop. It defines this function within the class, ensuring encapsulation and easier reuse in a program.


image.png


4. Creating and Using Objects

The program, in the Main class, demonstrates how to instantiate and use objects of the Laptop class. The two objects of the Laptop are instantiated by the use of new, and their constructor is invoked with the creation of their brand and price attributes as being initialized with specified values. Each object calls the displayDetails() method to display its details.


image.png


5. Separation and Output:

A blank line is printed between the details of two laptops for better readability of output. This allows distinguishing information to be shown for each object clearly.


image.png

After executing the program it shows the output with the detail of the laptops and their brand name and price.

This program shows how object oriented programming principles such as encapsulation and modularity are applied to create and manage real world entities like laptops.



Write a program that demonstrates the creation of a Movie class, its attributes, and methods, along with managing multiple objects in an array.

Here is the Java program that demonstrates the creation of a Movie class, its attributes, and methods, along with managing multiple objects in an array:


image.png

Here is an explanation of the program with functionality:

1. Defining the Movie Class:

The Movie class defines the structure and behaviour of a movie object. It includes two attributes:

  • title (a String): Represents the movie's title.
  • rating (a double): Represents the movie's rating.

The constructor initializes these attributes when an object is created, and the displayInfo() method is used to print the details of a movie.


image.png


2. Array of Movie Objects:

In the Main class, an array of type Movie is created to store three Movie objects. Arrays allow managing multiple objects of the same type efficiently.


image.png


3. Populating the Array:

The array is populated by creating three Movie objects using the new keyword and the constructor. Each object is initialized with specific values for title and rating. These objects are assigned to individual elements of the array.


image.png


4. Displaying Movie Details:

A for loop iterates through the array, and for each movie object, the displayInfo() method is called to print its details. To enhance readability, a blank line is added between the outputs of different movies.


image.png

This explanation] shows how the program defines a Movie class, creates multiple objects, stores them in an array, and uses methods to display their information. This modular and structured approach demonstrates the principles of object oriented programming effectively.



Write a program that demonstrates adding methods with calculations by creating a Product class.

Here is the Java program that demonstrates adding methods with calculations by creating a product class.


image.png

The program illustrates the definition and application of a Product class, encapsulating attributes, methods, and calculations. It demonstrates how to organize a Java program with object-oriented principles to efficiently handle and process information regarding products.

1. Defining the Product Class

The Product class is defined to model a product with three essential attributes:

  • name: Holds the name of the product such as "Iphone".
  • price: This is the price for a single unit of the product for example 799.99.
  • quantity: This is the number of units purchased or available for example 3.

The class makes use of a constructor to initialize these attributes each time a Product object is created. Therefore every product has its name, price, and quantity defined at the point of its creation.

image.png

The this keyword distinguishes instance variables from method parameters when they share the same name.


2. Calculating the Total Price

The class includes a method calculateTotalPrice() to compute the total price by multiplying the product's price by its quantity. This method encapsulates the calculation logic, making the code modular and reusable.

For example if the product price is $799.99 and quantity is 3 the total amount will be $2399.97.

image.png

This method enables easy modification or extension of the calculation logic in future without affecting any other parts of the program.


3. Displaying Product Details

The displayProduct() method prints out the product's attributes (name, price, and quantity) and also prints out the total price, which it obtains by calling calculateTotalPrice().

This method ensures all relevant product information is printed out in one coherent operation. The use of clear and descriptive System.out.println statements improves readability.


image.png

Encapsulating the display logic within the class improves the separation of concerns and promotes code reusability.


4. Managing Products in the Main Method

The main method demonstrates how to create and use objects of the Product class. In this case:

  1. A Product object called product is created, representing an Iphone priced at $799.99 with a quantity of 3.
  2. The displayProduct() method is called on the object to print its information and calculated total price.


image.png

The above code instantiates a Product object in one statement thus ensuring all attributes are defined with useful values.

This program shows how to create a class with attributes and methods that include calculations. It encapsulates logic within methods and organizes code to promote reusability and clarity.



Write a program that manages student records by creating a Student class

Here is the Java program that manages student records by creating a Student class.

image.png

This program shows how to work with student records and manage them using object-oriented principles in Java. It demonstrates how to create a Student class with attributes, methods, and handling multiple Student objects stored in an array. Below is a step-by-step breakdown of the program with detailed explanations and code references.


1. Class Design: The Student Class

The Student class contains all the data and behavior that characterizes a student. It contains:

Attributes

  • id: An integer to uniquely identify the student.
  • name: A string to represent the student's name.
  • marks: An array of integers containing the marks that the student obtained in various subjects.

Constructor

A constructor initializes the Student object by assigning values to the properties when the object is instantiated.


image.png

The constructor will ensure that at the moment of creation each Student object possesses valid and relevant data.


2. Method: Average Calculation

The calculateAverage() function calculates the average of marks stored in the marks array. It will use a for loop to iterate over the array, compute the total, and then divide it by the number of elements.

Logic

  1. Initialize variable total for holding sum of marks.
  2. Iterate over marks array by for loop, where each mark will be added to the total.
  3. Average should be calculated by dividing total by the size of an array.


image.png

  • It guarantees type safety by directly casting the returned value of calculateAverage() into double to ensure computation of average marks.
  • It can handle arrays of any dimension and hence is reusable in varying situations.

3. Method: Prints Student Details

The displayDetails() method prints the information of the student, such as Student ID, Name, marks, and average marks calculated by calling the calculateAverage() method.


image.png

Formatted Output

  • The Arrays.toString() method converts the marks array into a readable string format.
  • The printf function formats the average to two decimal places, ensuring a professional and clean output.

4. Main Method: Managing Student Objects

In the main method, we show how to use the Student class by creating and managing multiple objects.

Steps:

  1. Create an Array:
    An array of Student objects is created to manage records for multiple students. The array size is set to 3 to accommodate three students.


image.png

  1. Fill the Array:
    Every element in the array is assigned a new Student object with an ID, name, and marks.


image.png

  1. Print Student Information:
    A for-each loop traverses the array and invokes the displayDetails() method for each student to print their details.


image.png

This program simulates a simple student management system that can be extended to include more functionalities such as searching for students, updating marks, or sorting by averages. It is a good foundation for understanding how to manage collections of objects in real-life applications.



Write a program to simulate a simple Library Management System.

The program is designed to simulate a basic Library Management System where users can interact with a collection of books. It consists of three main classes: Book, Library, and LibraryManagementSystem. These classes work together to handle the core functions of the system such as adding books, searching for books, borrowing books, and returning them.


1. Book Class

The Book class is a simple representation of a book in the library. It encapsulates all the data about each of the books in the form of its ID, title, author, and availability. It also provides methods to interface with these data.

Attributes:


image.png

  • id: This is a unique identifier for each book. It helps differentiate one book from another in the system.
  • title: This refers to the book's title. (Example: "Animal Farm").
  • author: This stores the book author's name. An example: "George Orwell".
  • isAvailable: Boolean value which will indicate a particular book is available to lend or not. Usually by default, books become available to borrow at the point of their creation.

Constructor:


image.png

The constructor initializes a new Book object with the provided id, title, and author. It also sets isAvailable to true by default, meaning the book is initially available for borrowing.

Methods:

  • borrowBook():
    This method checks if the book is available (isAvailable is true). If it is available, it marks the book as borrowed by setting isAvailable to false. If the book is not available, it informs the user that the book is currently unavailable.


image.png

  • returnBook():
    This method marks the book as available again when it is returned. It changes the isAvailable flag back to true.


image.png

  • displayDetails():
    This method displays the details of the book, including its ID, title, author, and whether it is available for borrowing.


image.png

  • Getter methods:
    These methods allow the Library class (and any other class) to access the book ID, title, and availability status.


image.png


2. Library Class

The Library class is responsible for managing a collection of books. It stores all the books in an ArrayList. It also provides methods for adding books, displaying all books, searching for books, and allowing users to borrow or return books.

Attributes:

  • books: This is an ArrayList that contains all the books in the library. It gives dynamic storage for any number of books that are added to the library.

Constructor:


image.png

The constructor initializes an empty ArrayList of books which will later hold the books that are added to the library.

Methods:

  • addBook(Book book):
    This approach adds a book to the books list and prints out a confirmation message that states that a book has indeed been added to the library.


image.png

  • displayAllBooks()
    This will go through all books in the books list, calling displayDetails() on each one to print out details for each book in the library.


image.png

  • searchByTitle(String title):
    This method searches for a book by its title. If a match is found then it displays the details of the book. If no match is found then it prints a message. The message indicates that the book was not found.


image.png

  • borrowBook(int id):
    This method allows the user to borrow a book by its ID. If the book with the given ID is found then it calls the borrowBook() method of the Book class. If the book is not found then it prints a message. The message says that no book was found with the given ID.


image.png

  • returnBook(int id):
    This method allows the user to return a borrowed book by its ID. If the book with the given ID is found then it calls the returnBook() method of the Book class. If the book is not found then it prints a message. The message indicates that no book with that ID exists in the library.


image.png


3. LibraryManagementSystem (Main Class)

This is the main class that powers the program. It represents the entry point to the Library Management System. And from this the user interacts with the system via a menu of options. This class contains the main method. It initializes the library, adds some books and then display a menu. It allows the user to interact with the system.

Main Menu Loop:

The main method shows a menu of choices in a loop and lets the user perform several actions. The menu provides five choices:

  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

This is how the user interaction is structured:


image.png

  • View All Books: This will call the displayAllBooks() method of the Library class that prints all the books present in the library.


image.png

  • Search a Book for its Title: The following code prompts the user to enter a title and asks searchByTitle() to find any books with that title and print them.


image.png

  • Borrow a Book by ID: Prompts the user for a book ID and calls borrowBook() to borrow the book if available.


image.png

  • Return a Book by ID: It asks the user to input a book ID and calls returnBook() to return the borrowed book.


image.png

  • Exit: Exits the loop and ends the program.


image.png


This simple system demonstrates key object-oriented programming concepts such as encapsulation, object manipulation, and method calls, which make it an effective foundation for more complex systems like a real-world library management system.



I invite @wilmer1988, @josepha, @wuddi to join this learning challenge.



Sort:  
Loading...

Upvoted! Thank you for supporting witness @jswit.

Loading...

Coin Marketplace

STEEM 0.25
TRX 0.27
JST 0.040
BTC 96876.24
ETH 3451.68
SBD 1.58