Search code examples
javasuperclassextends

Java adding variables to super class


I have a general question: Is it possible to create a class, which is an original copy of another class, but contains additional variables?

For example I know that this is possible with a JPanel:

public class CustomPanel extends JPanel{
    int exampleVariable = 0;
}

This is possible without any problems. But can I do this with other classes too? In my case I want to do this with Image - but that doesn't seem to be possible, when I add extends Image I have to implement required methods, and that means I have to program a new Image class. Is it possible in another way?

Edit: My aim was to add a method to set the images name...


Solution

  • java.awt.Image is an abstract class.

    Therefore you must override all its methods when extending it.

    If you extend a non-abstract class, the methods are implemented, therefore you may choose to override them (as long as they're not final - or the class itself is not final).

    However, an abstract class is designed specifically to be extended by implementing its methods through @Override.

    Here is a good starting point to investigate further.