Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changed variable type in parent class

So I have this class called Card, in this class I have an Image, I then have several other classes that are inheriting this class and those classes as well.

I have decided to create a new class that extends Image instead now though and use that instead of the Image class in my parent Card class. However, because of this it has messed up all of the other classes that are passing in an Image variable.

Do I need to change all of the instances of the old Image class to the new CardImage class or is there another way around this?

Example:

public class A {
  private Image image;

  public A(Image image){
    this.image = image;
  }
}

public class B extends A{

  public B(Image image){
    super(image);
  }      
}

public class CardImage extends Image{
   public CardImage(){

   }
}
like image 260
bob565 Avatar asked Sep 27 '26 04:09

bob565


1 Answers

If your all classes will use only the CardImages then changing all of them can be meaningfull. But if only class A will use the CardImage then don't change anything. Just cast the Image to CardImage in A and use it. Because of each CardImages also is an Image, compiler won't push you to change parameter types.

public class A {
  private Image image;

  public A(Image image){
    this.image = image;
  }

  public void methodWhichNeedsCardImage() {
    if(image instanceof CardImage) {
         CardImage cImage = (CardImage) image;
    }
  }
} 
like image 176
rdonuk Avatar answered Sep 28 '26 16:09

rdonuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!