Skip to content
Advertisement

How to use methods in extended class and use them in main class

I am trying to create a method in an extended shape class and use it but it doesn’t work. Here is code what I am trying to do:

public class Try extends Application {
    @Override
    public void start(Stage arg0) throws Exception {
        Rectangle rectangle = new customRectangles(5);
        int i = rectangle.getObject();   //This doesn't work
        System.out.println(i);
    }
    
    class customRectangles extends Rectangle {
        int object = 0;

        customRectangles(int object){
            this.object = object;
        }

        public int getObject(){
            return object;
        }
    }
}

This isn’t complete code, most of it is removed. I have searched over web and couldn’t find anything so came to ask the question. Any help please.

Advertisement

Answer

Rectangle rectangle = new customRectangles(5);

means that the variable rectangle will only be a Rectangle. Hence only Rectangle methods will be seen. What you want to accomplish:

customRectangles rectangle = new customRectangles(5);

(Class names should start with uppercase letters)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement