In this tutorial, we will start this communication, talking about the Composition, which is simply the act of passing an object to another, to use its methods or attributes.
What is Composition in Java
It's just the act of instantiate or use a class/object in another. It's as if they communicate, exchange information in the object.That is, to reuse data without having to create more code for that.Simply pass the information - in the form of Object - to another, and this takes care of getting the data and how to work on it.
It is often said that composition is the act of delegating work to another object.
This makes your code more elegant, smaller and safer.
For what we use Composition in Java
As we mentioned in our introductory article on Classes and Objects , communication between your data is essential.As beginners, you will not notice this so much on small projects and beginners, but when you are a professional, you'll have a lot of headaches with it. Through a simplification of real projects, we show examples of pass codes and exercises for you to note the importance of composition in Java applications.
We gave the example of a company in different sectors at the initial article.
Hardly a large company will let you in charge of access to the entire system, especially the financial sector.
Usually this is held to seven keys. But as I explained there, they can simply share some data with you, as the final salary for each employee, for you to use in your class "Employee".
Noticed? You create your class, and makes your project uses data from another Object. And most importantly: is safe! You have no idea what happened there, how is it calculated things, the company's financial secrets etc.
For example, you create an object called "Geddy", from "Employee" class.
You send this object to the top-secret class "FinancialSector".
There, they calculate the paycheck, extra hours, taxes, benefits and others financial things that you should not care about.
After they modificate this object, your object will be changed already.
Great, isn't?
Due to object-orientation - and other things - this is possible.
In addition to safety, the Composition in Java makes it unnecessary to repeat code. You simply use what has already been done in another class / object, as is the case for example of the company.
Imagine if the programmer does not know Java? Would have to repeat the entire code of the financial sector within the class "Employee"?
Yes, he will.Believe me, there are bizarre things being done there.
Inheritance x Composition
More forward in our online Java course, we will talk about one of the most important, and controversial, and used feature of Java: Inheritance. This leads to data encapsulation.We will not go into much detail now but basically inheritance is a class ability to inherit data from another class.
For example, you create a mother class. Then you want to create a class like the mother - but with other features, you do not have to rewrite everything. Just make the child class inherits the parent class.
For example, we can create the "Car" class with attributes like "motor", "doors", "carburetor" etc., because all attributes are present in all cars. We then create "Beetle" class and the "Ferrari" class, both inherits "Car" class, because both are cars.
But it's clear that we will have to add more features in the "Ferrari" class because it has more attributes than the standard generic generalized "Car" class. But it's still a car.
This generalization, the fact that some classes need not inherited all the attributes of the parent class, also due to the fact that the move to change the parent class all classes daughters and a lot of other details, makes heritage use dangerous and not recommended. Some simply abhor inheritance.
We will not go into detail now, but composition use is harmless and well recommended. However, each case is unique.
Example use of Composition in Java
Exercise: Finding out if an Employee was late and your work time
In this example, we will create two additional classes: "Employee" and "Time"Let's create a worker, 'geddyLee', create an object to store the time he arrived 'arrivedHour' and the time he left 'outHour'.
From the time of arrival, we will check if it arrived late (after 8am) and using information from the two objects of class "Time", we know how long he worked and store this information in the variable "workedTime' in 'geddyLee object from "Employee " class, and we will store the information if it has arrived late
That is, we will exchange information between these objects!
HourControl.java
This is our main class, which has the main method.
In the main, simply create objects Employee and Time mentioned in the statement.
We began the objects of "Time" now with their values (hour, minute, second). You can change to your liking, for testing or ask the user, via the Scanner class.
Then, for information, it displays arrival time, output and total time worked, in hours.
The main is very small and clean, as it should be.
Time.java
This class receives three integer: hours, minutes and seconds, and makes treatment.
Treatment is: the hours must be integers between 0 and 23, minutes and seconds must be integers between 0 and 59.
If not, an exception is thrown (artifice to show that an error occurred and the application is closed).
Try putting the wrong date to see the error message.
The methods in this class are simple getters .
Worker.java
This class will receive information from other objects, it will gets objects of "Time" class.
Let's review its methods:
- public double lateTime(Time arrivalTime)
Let's find out the official time converting the delayed arrival time in seconds.
Simply transform the worker arrive time in seconds:
arrivalTime.getHour () * 60 * 60 + arrivalTime.getMinute () * 60 + arrivalTime.getSecond ()
And subtract the time that he should come in the company (8h00min):
8 * 3600.0
And divide by 3600.0, and the result is a double that represents the late hours.
- public double workedTime(Time arrivalTime, Time outTime)
To calculate the time worked for an employee, we take into account only the hours worked.
First, we transform the time of departure and arrival time in minutes and subtract this value:
(outTime.getHour () * 60 + outTime.getMinute ()) - (arrivalTime.getHour () * 60 + arrivalTime.getMinute ())
Now we have the difference between the times of arrival and departure in minutes.
Then, divide by 60.0 to get all the time worked in hours.
If this time is negative, it is because you put a release date before the date of arrival.
Then an error with the explanation, application is launched and closed.
- public double getWorkedHours()
A simple example to get, which returns the variable 'workedTime'.
Code of our Java program:
HourControl.java
public class controleHorario {
public static void main(String[] args) {
Time arrivalTime = new Time(8, 0, 1);
Time outTime = new Time(9, 30, 0);
Worker geddyLee = new Worker("Geddy Lee", arrivalTime, outTime);
System.out.println("Arrival time: " + arrivalTime.toString());
System.out.println("Out time: " + outTime.toString());
System.out.printf("Worked hours %.1f",geddyLee.getWorkedHours());
}
}
Time.java
public class Hora {
private int hours,
minutes,
seconds;
public Hora (int hours, int minutes, int seconds){
//hour time checker
if(hours>=0 && hours <24 )
this.hours = hours;
else
throw new IllegalArgumentException("Invalid hour.");
//minute time checker
if(minutes >=0 && minutes < 60)
this.minutes = minutes;
else
throw new IllegalArgumentException("Invalid minutes.");
//seconds time checker
if( seconds >=0 && seconds < 60)
this.seconds = seconds;
else
throw new IllegalArgumentException("Invalid secondes.");
}
public int getHour(){
return this.hours;
}
public int getMinute(){
return this.minutes;
}
public int getSecond(){
return this.seconds;
}
}
Worker.java
public class Worker {
private String name;
private boolean isLate;
private double workedTime, lateTime;
public Worker(String name, Time arrivalTime, Time outTime){
this.name=name;
this.lateTime = lateTime(arrivalTime);
if(this.lateTime > 0)
this.isLate=true;
if(isLate){
System.out.println("Worker '" + this.name + "' isLate. ");
}
this.workedTime = workedHours(arrivalTime, outTime);
}
public double lateTime(Time arrivalTime){
return ((arrivalTime.getHour()*60*60 + arrivalTime.getMinute()*60 + arrivalTime.getSecond()) - 8*3600.0)/3600.0;
}
public double workedHours(Time arrivalTime, Time outTime){
double hours = ( (outTime.getHour()*60 + outTime.getMinute()) - (arrivalTime.getHour()*60 + arrivalTime.getMinute()) )/60.0;
if(hours < 0)
throw new IllegalArgumentException("Arrival time after out time.");
return hours;
}
public double getWorkedHours(){
return this.workedTime;
}
}
Exercise: Java Application for a Supermarket
You have been selected to create an app - in Java, of course - to a supermarket.
The owner of the property asked the functionality "Promotion for you", which works as follows:
After 20h, all products are 10% off.
On Saturdays and Sundays the off is worth the whole day.
That is, besides having a class for products from the supermarket, you should create another with the time of purchase.
Use the technique of composition to pass the purchase time object to the object related to the product that's being purchased. Thus, the object product price is calculated based on the daytime and day of the week.
In its main, ask for the product price, day of week and time of purchase (hour, minute and seconds), and return the final value of the product based on these data.
PS: In a real application, it would not be required to provide such data. They were obtained by a barcode reader to know the price of the product, and would take the system time, to fill in the data for the time.
We ask, however, for the sake of learning, since you should not have such a barcode reader at home ...
1 comment:
Thanks for sharing this- good Information! Keep up the great work, we look forward to reading more from you in the future!
Regards,
Java Online Training
Post a Comment