SlinnShady
SlinnShady

Reputation: 515

Override not having expected effect on class

I am testing out extending a class and overriding functions. With the below I get no compile errors yet when I call JonsClass2.jonsCalcFromClass(2) I still get the response from JonsClass2 not the override from JonsClass3 that I expected.

As an aside I am having to make these calls from main using JonsClass2 JC2 = new JonsClass2(); then JC2.jonsCalcFromClass(2); else the compiler complains that I am calling a non static from a static context.

class JonsClass3 extends JonsClass2 {

    @Override
    protected int jonsCalcFromClass(int a) {
        if (a==2) System.out.print("JonsClass3 Called from main using 2 as passed variable  ");
        if (a==1) System.out.print("JonsClass3  from main using 1 as passed variable  ");
        int c = (a + 2);
        return c;
    }

    @Override
    protected double jonsCalcFromClass(double b) {
        System.out.print("This is double line being called in JonsClass3> ");
        double c = (b + 300.10);
        return c;
    }

}

class JonsClass2 {

    protected int jonsCalcFromClass(int a) {
        System.out.print("This is the int line from JonsClass2 being called > ");
        int c = (a + 2);
        return c;
    }

    protected double jonsCalcFromClass(double b) {
        System.out.print("This is double line being called in JonsClass2> ");
        double c = (b + 3.10);
        return c;
    }

}

Upvotes: 0

Views: 147

Answers (2)

MoRtEzA TM
MoRtEzA TM

Reputation: 106

the compiler complains that I am calling a non static from a static context.

We can't call non-static methods from a static method (like main) directly. because a static method is a class' method. but a non-static method is object method so we should call it on an object. so:

public static void main(String[] args) { 
  jonsCalcFromClass(1) // compile error

  JonsClass2 JC2 = new JonsClass3()
  JC2.jonsCalcFromClass(1) // correct
}

If you want polymorphism behaviour you should do this: JonsClass2 JC2 = new JonsClass3 ();

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

Pay attention on what instanse you create.

JonsClass2 js2 = new JonsClass2();
JonsClass2 js3 = new JonsClass3();
js2.jonsCalcFromClass(2);   // This is the int line from JonsClass2 being called >
js3.jonsCalcFromClass(2);   //JonsClass3 Called from main using 2 as passed variable 

In your example onsClass2 JC2 = new JonsClass2(); you create instance of JonsClass2, so methods from JonsClass3 will not be called.

Upvotes: 2

Related Questions