Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Java programmer, basic java composition

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

like image 795
ngunha02 Avatar asked Jun 26 '12 08:06

ngunha02


People also ask

What is composition in Java programming?

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.

What are the 4 basic things in Java?

The main ideas behind Java's Object-Oriented Programming, OOP concepts include abstraction, encapsulation, inheritance and polymorphism.

What is new in Java programming?

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.

What is composition example?

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.


2 Answers

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;
}
like image 142
Sergey Kalinichenko Avatar answered Sep 28 '22 15:09

Sergey Kalinichenko


if the paper tray is empty, then in class PaperTray the method isEmpty() will return false

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.

like image 38
Péter Török Avatar answered Sep 28 '22 14:09

Péter Török