SLC S22 Week2 || The Object Approach In JAVA
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:
Quality | Description |
---|---|
Validity | The software performs the tasks for which it was designed. |
Extensibility | Ability to integrate new specifications without significant modifications. |
Reusability | Utilization of libraries to avoid redundant code. |
Robustness | Ability to function even under abnormal conditions. |
Modularity | The 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:
- Difficult to write large applications.
- Difficult to maintain data consistency over time.
- Risks associated with large-scale data sharing.
- Duplication of common processing tasks, which does not promote code reuse.
- Global data.
- High coupling between data.
- Etc.
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:
- Functions, procedures, and other instruction sequences access a shared area where data is stored. This dissociation between data and functions creates difficulties when data structures need to be changed.
- In procedural languages, procedures call one another and can act on the same data, causing side effects.
- Functions and procedures operate "remotely" on the data.
- Dissociation between data and functions => issues when changing data structures.
- In procedural programming, procedures call one another and can modify the same data => problem arises when modifying a procedure: How was it called?
- Structured programming, with its accompanying methods, is suited to solving a given problem. However, if revolutionary changes are introduced, the underlying design may collapse. Structured programming is not well-suited for radical and frequent modifications. Unfortunately, it is often observed in practice that even a well-performing software must continuously evolve to remain viable. The well-known joke among "hackers" is often true: "Any finished program is obsolete."
- This need for change in modern software has led to the development of a new way of programming: object-oriented programming.
II.4. Object-oriented programming:
Goals:
- Improve the reuse of existing tools.
- Promote the specialization of these same tools.
- Move away from the machine and get closer to the problem to be solved.
- Develop a better approach to problem-solving.
- Find a new way to think about decomposing problems and elaborating solutions.
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
Identity:
The identity of an object distinguishes it from other objects.State:
The state encompasses the instantaneous values of all the attributes of an object. Attributes are pieces of information that define the object.
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.
- Behavior:
The behavior of an object is defined by the set of operations it can execute in response to messages sent by other objects. A message is a request to execute an operation.
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:
- When objects share the same attributes and behaviors, they are grouped into a family called a class.
- A class is like a blueprint from which we can generate a set of objects sharing common attributes and methods.
- Objects in a class are instances of that class.
- Instantiation is the process of creating an object from a class.
- Two instances of the same class can have different attribute values but share the same methods.
III.3. Example: Object-Class Relationship
To better understand what an object is, let’s use the example of a car:
- "Mycar" is an object, a specific instance that exists and can be used.
- "Mycar" belongs to the type or category of 'car.'
- 'Cars' form a class of objects (Class) with shared characteristics: they are made of metal, they transport passengers, etc.
- However, I cannot use the generic 'cars' class directly.
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
- How many classes are there?
- Classes depend on how we classify the entities in a system.
Examples of Classifications:
- Classification 1: By functional role.
- Classification 2: By physical properties.
- Classification 3: By domain of application.
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.
- Think of an object as an enhanced variable: it stores data, but you can also "query" it and ask it to perform operations on itself.
- In theory, any conceptual component of a problem you are trying to solve (a dog, a building, an administrative service, etc.) can be represented as an object in a program.
2.A program is a collection of objects communicating with one another by sending messages.
- To make an object perform a task, you "send a message" to it.
- More concretely, you can think of a message as calling a method (or function) belonging to a specific object.
3.Each object has its own memory space, composed of other objects.
- In other words, a new type of object is created by bundling together existing objects.
- This way, the complexity of a program is hidden behind the simplicity of the objects being used.
4.Each object is of a specific type.
- In object-oriented terminology, every object is an instance of a class, where "class" is synonymous with "type."
- The most important defining feature of a class is: What messages can it receive?
5.All objects of a specific type can receive the same message.
- This characteristic is deeply significant, as you will understand later when exploring the principles of polymorphism and inheritance in object-oriented programming.
III.5. Graphical Representation of Classes
Each class is depicted as a rectangle divided into three compartments:
- Class Name
- Attributes
- 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:
- Compile:
javac Main.java Point.java
- Run:
java Main
- Classes in Java are used to group data (fields) and behavior (methods).
- Objects are created from classes and interact with each other by calling methods.
- Java promotes encapsulation, reusability, and modular design through the use of classes and objects.
This approach simplifies complex systems by breaking them down into manageable components.
Homework :
Task1: (1 points)
Which of the following statements about Java classes and objects is true?
1.What is a class in Java?
- (A) A blueprint for creating objects.
- (B) A specific instance of an object.
- (C) A library of pre-written code.
- (D) A type of variable used to store data.
2.What does the new
keyword do in Java?
- (A) Declares a new variable.
- (B) Creates a new object of a class.
- (C) Adds a new method to a class.
- (D) Initializes a static variable.
3.Which of the following statements is true about attributes in a class?
- (A) Attributes are also known as methods.
- (B) Attributes must always be
public
. - (C) Attributes store data for an object.
- (D) Attributes are optional in a class.
4.What is the purpose of a constructor in a class?
- (A) To define the behavior of an object.
- (B) To initialize the fields of a class.
- (C) To execute code when a method is called.
- (D) To create a copy of an existing object.
Task2: (1.25 points)
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 attributesbrand
(a string) andprice
(a double).Implement a constructor to initialize these attributes and a method
displayDetails()
to print the brand and price of the laptop.In the
main
method, create two instances of theLaptop
class with different values for the attributes and call thedisplayDetails()
method for each object to produce and display the corresponding output.
Task3: (1.25 points)
Write a program that demonstrates the creation of a
Movie
class, its attributes, and methods, along with managing multiple objects in an array. Define theMovie
class with the attributestitle
(a string) andrating
(a double).Implement a constructor to initialize these attributes and a method
displayInfo()
to print the title and rating of the movie.In the
main
method, create an array to store threeMovie
objects, populate the array with details for each movie, and call thedisplayInfo()
method for each object to display their respective details.
Task4: (1.5 points)
Write a program that demonstrates adding methods with calculations by creating a
Product
class. The class should include the attributesname
(a string),price
(a double), andquantity
(an integer).Implement a constructor to initialize these attributes and a method
calculateTotalPrice()
to compute the total price as the product ofprice
andquantity
. Additionally, create a methoddisplayProduct()
to print the product's details, including the total price.In the
main
method, create an instance of theProduct
class, and call thedisplayProduct()
method to output the product's details and its total price.
Task5: (2 points)
Write a program that manages student records by creating a
Student
class. The class should have the attributesid
(an integer),name
(a string), andmarks
(an array of integers).Implement a constructor to initialize these attributes and a method
calculateAverage()
to compute and return the average of the marks. Additionally, create a methoddisplayDetails()
to print the student's details, including their average marks.In the
main
method, create an array of threeStudent
objects, populate the array with details for each student, and call thedisplayDetails()
method for each object to display their respective information, including their average marks.
Task6: (3 points)
Write a program to simulate a simple Library Management System. The program should include the following:
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()
: SetsisAvailable
tofalse
if the book is available, otherwise prints that the book is not available.returnBook()
: SetsisAvailable
totrue
.displayDetails()
: Prints the book's details, including its availability.
- Attributes:
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.
- Attributes:
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