-2

Here is the given code:

class Super {
    protected int n;

    Super(int n){
        this.n=n;
    }

    public void print(){
        System.out.println("n="+n);
    }
}

class Sub {
    Sub(int m){
        Super.n=m;
    }
}

class Test{
    public static void main(String[] args){
        Sub s= new Sub(10);
        s.print();
    }
}

I am getting these errors:

Main.java:19: error: non-static variable n cannot be referenced from a static context
Super.n=m;
...........^
Main.java:25: error: cannot find symbol
s.print();

Can someone please tell me why these errors occur?

zx485
  • 28,498
  • 28
  • 50
  • 59

2 Answers2

1

Your problem is the Sub class:

class Sub {
    Sub(int m){
        Super.n=m; // <- this line of code!
    }
}

Super.n is a syntax to access a variable defined in a class scope. In java, we call this kind of variable static variables.

To correct this problem, you have to do the following:

// With the extends Super, you are inheriting properies and methods
// from Super class
class Sub extends Super {
    Sub(int m){
        // Now you are calling a constructor from the parent             
        super(m);
    }
}
rafaelim
  • 644
  • 6
  • 13
0

Sub needs to actually inherit Super.

public class Sub extends Super would make Super's variables accessible from Sub.

Language reference:

Inheritance in Java

Athena
  • 3,200
  • 3
  • 27
  • 35