Search code examples
javastatic-methodsnon-static

How to access protected inherited non static method in static method(ex main method) of other package?


By creating instance of parent class we can't access its inherited method in other package as it is not direct inheritance. Even directly we cant use non static because our child method is static whereas parent class method isn't. ex

package classacees;

public class Thread1 {

protected  double sub(double a, double b) {

return (a - b);

}

and...

package example;

import classacees.Thread1;

public class Ece extends Thread1 {

        public static  void main(String[] args) {

double n=sub(3,2);  // error -> cant make a static reference to non static method.
System.out.println(n);

}

Solution

  • First of all you can't call an instance method directly like double n=sub(3,2); ; for that you need an object.

    For your query you can do so by accessing the protected method from the instance of the child class:

        public class Ece extends Thread1 {
        public static void main(String[] args) {
            Ece ece = new Ece();
            double n = ece.sub(4, 9);
            System.out.println(n);
        }
    
    }
    

    Hope this helps..