-1

I'm trying to understand how composition in Java works and I'm getting stuck. I have a program that instantiates a Customer object who has a Computer object as an instance variable. There are two types of Computer objects in my program, a Desktop and a Laptop subclass, so I have my Desktop class extending Computer and my Laptop class also extending Computer. I have my Computer class as an abstract class but I know that you can't instantiate an abstract object. I'm not sure how to instantiate the Computer object in my Customer class. Any insight is appreciated ! Example code:

public class Customer
{
   private String name;
   private Computer computer;

   public Customer(String n)
   {
      setName(n);
      this.computer = new Computer(); //Can't do this b/c Computer is abstract
   }

   //Setters and getters for name
   public Computer getComputer()
   {
      return new Computer(this.computer);
   }

   public void setComputer(Computer computer)
   {
      this.computer = new Computer(computer);
   }

}
public abstract class Computer{
}

public class Desktop extends Computer{
}

public class Laptop extends Computer{

}
  • You also don't have a `Computer` constructor that takes a `Computer` instance. So, `this.computer = new Computer(computer);` and `return new Computer(this.computer);` are not valid either. – Elliott Frisch May 04 '20 at 00:14
  • As you say yourself, you cannot instance an abstract class but you can do either `this.computer = new Desktop();` or `this.computer = new Laptop();`. This will work since they both extends Computer and can be used any place that would take a Computer. – Pete May 04 '20 at 00:15
  • Oh I didn't realize you could simply just instantiate the subclass like that ! Thank you, this was really helpful ! – soondubu247 May 04 '20 at 00:21

2 Answers2

0

Yes you are right. You cannot instantiate the abstract class Computer(). Instead, you can do

this.computer = new Laptop() 
this.computer = new Desktop()

depending on which they have.

Jackson
  • 1,213
  • 1
  • 4
  • 14
0

The way you solve this problem is that your Constructor should also take a Computer argument

   public Customer(String n, Computer c)
   {
      setName(n);
      this.computer = c;
   }

But there are a lot of reasons to prefer POJOs (Plain Old Java Objects) with only a null constructor over classes that demand the composition elements at construct-type. For more information, see: What's the advantage of POJO?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80