I am a new computer programming student. I watched a video about Java, basic composition, and the guy in the video made an example about this topic like this:
public class PaperTray
{
int pages = 0;
....
public boolean isEmpty()
{
return pages > 0;
}
}
public class Printer extends Machine
{
private PaperTray paperTray = new PaperTray();
....
public void print(int copies)
{
....
while(copies > 0 && !paperTray.isEmpty() )
{
System.out.println("some text to print");
copies--;
}
if(paperTray.isEmpty())
{
System.out.println("load paper");
}
}
My question is if the paper tray is empty, then in class PaperTray the method isEmpty() will return false. Therefore, the if statement in the class Printer will not be executed. And if the paper tray is not empty, the method isEmpty() in class PaperTray will return true, so the while statement in the class Printer will not be executed. Am I wrong, or the instructor in the video clip made some mistakes?
Thank you
Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse.
The main ideas behind Java's Object-Oriented Programming, OOP concepts include abstraction, encapsulation, inheritance and polymorphism.
new is a Java keyword. It creates a Java object and allocates memory for it on the heap. new is also used for array creation, as arrays are also objects.
In composition, both entities are dependent on each other. When there is a composition between two entities, the composed object cannot exist without the other entity. For example, A library can have no. of books on the same or different subjects.
The logic of the isEmpty
does not make sense: I wold expect either
public boolean isEmpty() {
return pages == 0;
}
or
public boolean isNotEmpty() {
return pages > 0;
}
if the paper tray is empty, then in class
PaperTray
the methodisEmpty()
will returnfalse
It should return true
(for any sensible implementation, that is :-). For a method called isEmpty()
, common sense dictates that it returns true
when the enclosing object / collection is empty, and false
when it is not empty.
In other words, the implementation you show above has a bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With