SLC S22 Week2 || The Object Approach In JAVA

kouba01 -


Created by @kouba01 using Canva & PhotoFilter

Hello Steemians

Welcome to the second week of the Steemit Learning Challenge Season 22, where we continue our journey into the world of object-oriented programming (OOP) with Java. This week focuses on deepening your understanding of Java by exploring key software engineering principles and the essential concepts of classes and objects.

Throughout this week, you will learn how to apply fundamental programming approaches, from understanding modularity and reusability to delving into the structure and behavior of objects. By designing and implementing Java classes, you will build a strong foundation for creating robust and maintainable software.

This course emphasizes practical learning with hands-on examples and exercises that showcase the flexibility and power of Java. By the end of this week, you will have the skills to create reusable and modular code, design classes that represent real-world entities, and write programs that demonstrate the core principles of object-oriented programming.

Get ready to transform your programming skills as we explore the practical applications of OOP in Java. Together, let’s continue this exciting journey toward mastering one of the most versatile programming languages!

I. Key Principles of Software Engineering

In the lifecycle of software, there is a development phase and a maintenance phase, which involves evolving the software and/or updating it. The integration of new modules or the modification of a part of the software is often a complex task, as it may involve multiple functions or modules of the system.

Some of the qualities of software include the following:

QualityDescription
ValidityThe software performs the tasks for which it was designed.
ExtensibilityAbility to integrate new specifications without significant modifications.
ReusabilityUtilization of libraries to avoid redundant code.
RobustnessAbility to function even under abnormal conditions.
ModularityThe software's architecture should be clear to enable changes without major repercussions.

The different modules of software must form independent entities, and a modification should affect only one logical entity.

II. Programming Approaches

II.1. Non-procedural programming:

The first programming languages generally consisted of a sequence of instructions executed linearly: this is called non-procedural programming.

Characteristics:


II.2. Procedural programming:

Procedural programming (e.g., C, Pascal, Basic) consists of a sequence of instructions (often grouped into functions) executed by a machine. These instructions aim to manipulate data to produce a certain effect.

Characteristics:


II.4. Object-oriented programming:

Goals:

A new entity is created, called an object, which groups functions and data. There are few or no global variables.
A program is viewed as a collection of entities, like a society of entities. During execution, these entities collaborate by sending messages to each other for a common goal.

In this model, there is a strong link between the data and the functions that access them (whether for consulting or modifying): this reflects the natural segmentation of the system.

What is an object? What does it represent?

III. Concept of Class and Instance

III.1. Concept of an Object:

An object represents an entity in the real world or in a virtual world (in the case of intangible objects) that is characterized by an identity, significant states, and behavior.

Object = State + Behavior + Identity

For example, a car object has attributes such as color, weight, and horsepower. The state of the object changes over time, such as when fuel decreases or temperature varies during use.

In programming terms:
An object consists of a block of memory organized into fields, along with a set of functions to consult or modify those fields.


III.2. Concept of a Class:


III.3. Example: Object-Class Relationship

To better understand what an object is, let’s use the example of a car:

To create "my car," I use the blueprint of the Car class (like a mold) and instantiate an object, naming it MyCar.


III.4. Object-Oriented Approach

  1. How many classes are there?

Examples of Classifications:

Note:

➢ The real world consists of a vast number of interacting objects.
➢ To reduce this complexity, similar elements are grouped together, and higher-level structures are identified, free of unnecessary details.
➢ A class is a set of objects that share the same structure, behavior, relationships, and semantics.

These characteristics form the foundation of a purely object-oriented approach:


1.Everything is an object.


2.A program is a collection of objects communicating with one another by sending messages.


3.Each object has its own memory space, composed of other objects.


4.Each object is of a specific type.


5.All objects of a specific type can receive the same message.


III.5. Graphical Representation of Classes

Each class is depicted as a rectangle divided into three compartments:

  1. Class Name
  2. Attributes
  3. Operations (Methods)

Example:
The class Motorcycle includes attributes like Color, EngineCapacity, and MaxSpeed. It also groups operations such as Start(), Accelerate(), and Brake().

IV. Classes in Java

IV.1. Declaration:

In Java, a class is a blueprint used to define objects. It contains fields (attributes) to store data and methods (functions) to define the behavior of the objects.
A class is defined using the class keyword followed by its name, which usually starts with a capital letter. The class body, including fields and methods, is enclosed within curly braces.

Example of a Point class:


IV.2. Using the Class

IV.2.1. Creating an Instance of a Class:

Once a class is defined, objects (or instances) can be created from it using the new keyword.

Example of creating and using a Point object:


IV.3. Scope of Methods and Fields

In Java, the dot . operator is used to access fields and methods of an object. Fields can be marked as private, making them accessible only within the class, while public methods allow access from outside the class.

Example:

Point p = new Point(3, 4);
p.display(); // Accessing the display method

IV.4. Passing Objects to Methods:

Objects can be passed as arguments to methods. In Java, objects are passed by reference, allowing modifications without duplicating the object.

Example:

public boolean coincide(Point other) {
    return this.x == other.x && this.y == other.y;
}

Usage:

Point p1 = new Point(2, 3);
Point p2 = new Point(2, 3);

if (p1.coincide(p2)) {
    System.out.println("The points are identical.");
}

IV.5. Methods Returning Objects of the Same Class:

A method can return an object of the same class. For instance, to calculate the midpoint between two points:

public Point midpoint(Point other) {
    int midX = (this.x + other.x) / 2;
    int midY = (this.y + other.y) / 2;
    return new Point(midX, midY);
}

Usage:

Point mid = p1.midpoint(p2);
mid.display();

IV.6. Nested Classes

If a class needs a complex attribute, it can include another class as a field. For example, a Person class may include a Date class for the date of birth.

Example:

class Date {
    int day, month, year;

    public Date(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public void display() {
        System.out.println(day + "/" + month + "/" + year);
    }
}

class Person {
    String name;
    String id;
    Date birthDate;

    public Person(String name, String id, Date birthDate) {
        this.name = name;
        this.id = id;
        this.birthDate = birthDate;
    }

    public void display() {
        System.out.println("Name: " + name + ", ID: " + id);
        System.out.print("Birthdate: ");
        birthDate.display();
    }
}

Usage:

Date birth = new Date(07, 10, 1984);
Person person = new Person("Bilel Bouchamia", "123456", birth);
person.display();

IV.7. Composition of Classes

When a class includes another class as a member, it is called composition. This allows building complex objects from simpler ones.


IV.8. File Organization in Java

In Java, each class is typically defined in its own file. The file name matches the class name and has a .java extension.

Example:

Compilation and Execution:


Homework :

Task1: (1 points)

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

1.What is a class in Java?


2.What does the new keyword do in Java?


3.Which of the following statements is true about attributes in a class?


4.What is the purpose of a constructor in a class?

Task2: (1.25 points)

Task3: (1.25 points)

Task4: (1.5 points)

Task5: (2 points)

Task6: (3 points)

Write a program to simulate a simple Library Management System. The program should include the following:

  1. Book Class

    • Attributes:
      • id (int): A unique identifier for each book.
      • title (String): The book’s title.
      • author (String): The author of the book.
      • isAvailable (boolean): Indicates whether the book is available or borrowed.
    • Methods:
      • A constructor to initialize all attributes.
      • borrowBook(): Sets isAvailable to false if the book is available, otherwise prints that the book is not available.
      • returnBook(): Sets isAvailable to true.
      • displayDetails(): Prints the book's details, including its availability.
  2. Library Class

    • Attributes:
      • books (ArrayList< Book >): A collection of books in the library.
    • Methods:
      • addBook(Book book): Adds a new book to the library.
      • displayAllBooks(): Displays the details of all books in the library.
      • searchByTitle(String title): Searches for a book by its title and displays its details if found.
      • borrowBook(int id): Allows a user to borrow a book by its ID if available.
      • returnBook(int id): Allows a user to return a book by its ID.
  3. Main Method

    • Create a library with a few initial books.
    • Allow the user to perform the following actions:
      • View all books.
      • Search for a book by title.
      • Borrow a book by ID.
      • Return a book by ID.

Contest Guidelines

Post can be written in any community or in your own blog.

Post must be #steemexclusive.

Use the following title: SLC S22 Week2 || The Object Approach In JAVA

Participants must be verified and active users on the platform.

The images used must be the author's own or free of copyright. (Don't forget to include the source.)

Participants should not use any bot voting services, do not engage in vote buying.

The participation schedule is between Monday, December 23, 2024 at 00:00 UTC to Sunday, - December 29, 2024 at 23:59 UTC.

Community moderators would leave quality ratings of your articles and likely upvotes.

The publication can be in any language.

Plagiarism and use of AI is prohibited.

Use the tags #dynamicdevs-s22w2 , #country (example- #tunisia) #steemexclusive.

Use the #burnsteem25 tag only if you have set the 25% payee to @null.

Post the link to your entry in the comments section of this contest post. (very important).

Invite at least 3 friends to participate in this contest.

Strive to leave valuable feedback on other people's entries.

Share your post on Twitter and drop the link as a comment on your post.

Rewards

SC01/SC02 would be checking on the entire 15 participating Teaching Teams and Challengers and upvoting outstanding content. Upvote is not guaranteed for all articles. Kindly take note.

At the end of the week, we would nominate the top 4 users who had performed well in the contest and would be eligible for votes from SC01/SC02.

Important Notice: The selection of the four would be based solely on the quality of their post. Number of comments is no longer a factor to be considered.


Best Regards,
Dynamic Devs Team