0

I am very confused with this . can any one clear me why it was not allowing the code that i have placed n comments

package pack1;
public class A {
  protected void m1() {
    System.out.println("This is very imp point");
}


package pack2;
import pack1.A;
class B extends A {
  public static void main(String arg[]) {
    // A a1 = new A();
    //a1.m1();
    B b1 = new B();
    b1.m1();
    //A a2 = new B();
    //a2.m1(); }
  }
}
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
  • 1
    Please take the time to properly format your code. SO users are helpful, but not so helpful that they will read badly formatted code, format it for you, then solve your problem. – Arc676 Nov 04 '15 at 13:26

2 Answers2

1

Method m1 is protected, so it's accessible across packages to child classes.

Therefore, instances of B will be able to invoke or @Override m1.

Not so main static methods, even if pertaining to class B: the scope is different.

You can either make m1 public in A, or invoke it within your instance of B (e.g. in the constructor, etc.).

You can also override A's m1 in B and give it less access restrictions, thus making it public in this instance: then you could access it on an instance of B from your main method as you're trying to do.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

You can access the protected members declared in A within B, but only for instances of B or subclasses of B. Check out this answer

Community
  • 1
  • 1
Harsh Poddar
  • 2,394
  • 18
  • 17