0

Is there a way to call test() in class a from class b object created in class c ?

class a {
 void test(){
   System.out.println("in a");
  }
}

 class b extends a {
   void test(){
     System.out.println("in b");
   }
}

public class c{
 public static void main(String[] args) {
   b refb = new b();
   refb.test();
  }
}
Jenz
  • 8,280
  • 7
  • 44
  • 77
Jayadeep
  • 26
  • 3

2 Answers2

2

You can do that only within the test() method of class b like following.

class b extends a {
   void test(){
     super.test();
     System.out.println("in b");
   }
}
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

In Java, all non static private methods are virtual by default. So, there's no way to invoke a#test from b instance unless you modify b#test. The only way to do it (by your current design) is using an instance of a:

public class c{
    public static void main(String[] args) {
        b refb = new b();
        // code to call test() in class a
        //this is the only way you have in Java
        a refA = new a();
        a.test();
    }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332