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!
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.
The first programming languages generally consisted of a sequence of instructions executed linearly: this is called non-procedural programming.
Characteristics:
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:
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?
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.
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.
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
.
Examples of Classifications:
➢ 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.
Each class is depicted as a rectangle divided into three compartments:
Example:
The class Motorcycle
includes attributes like Color
, EngineCapacity
, and MaxSpeed
. It also groups operations such as Start()
, Accelerate()
, and Brake()
.
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:
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:
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
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.");
}
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();
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();
When a class includes another class as a member, it is called composition. This allows building complex objects from simpler ones.
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:
javac Main.java Point.java
java Main
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?
public
.4.What is the purpose of a constructor in a class?
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 attributes brand
(a string) and price
(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 the Laptop
class with different values for the attributes and call the displayDetails()
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 the Movie
class with the attributes title
(a string) and rating
(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 three Movie
objects, populate the array with details for each movie, and call the displayInfo()
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 attributes name
(a string), price
(a double), and quantity
(an integer).
Implement a constructor to initialize these attributes and a method calculateTotalPrice()
to compute the total price as the product of price
and quantity
. Additionally, create a method displayProduct()
to print the product's details, including the total price.
In the main
method, create an instance of the Product
class, and call the displayProduct()
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 attributes id
(an integer), name
(a string), and marks
(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 method displayDetails()
to print the student's details, including their average marks.
In the main
method, create an array of three Student
objects, populate the array with details for each student, and call the displayDetails()
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
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.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.Library Class
books
(ArrayList< Book >): A collection of books in the library.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.Main Method
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.
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