Home > Enterprise >  Can a class have an abstract class as attribute in Java?
Can a class have an abstract class as attribute in Java?

Time:04-01

I have an abstract class Product

public abstract class Product implements Serializable {
   private Integer id;
   private LocalDateTime creationDate;
   private LocalDateTime updateDate;
   //constructors etc..
}

then I have multiple child classes that extend Product and an Ad class which lists the products. My question is: can I use the Product class as an attribute? so it could be instantiated with the different child classes like this:

public class Ad implements Serializable {
   private Integer id;
   private Product product;
   //constructors and methods..
}


Ad example = new Ad(1,childClass);

CodePudding user response:

Your question is whether you can use the Product class which is the abstract class as an attribute so it could be initiated with the different child class implementation of it ? Answer is yes!

I will add a simple example below:

Abstract class

public abstract class AbstractClass {

  abstract void test();

}

Child class

public class ChildClass extends AbstractClass {

  @Override
  void test() {

  }

}

Example usage

public class Example {

  private static AbstractClass abstractClass;

  public static void main(String[] args) {
    abstractClass = new ChildClass();
  }

}

Hope this answers your question.

CodePudding user response:

Yes, member field can be an abstract type

  • Related