-1
public class A {
    public void f(A a) {
        System.out.print("in A ");
    }
}

public class B extends A {

    public static void main(String[] args) {
        B b = new B();
        A a = new A();
        b.f(b);
        b.f(a);
    }
}

Why by adding the following method in B class there will be a compilation error?

It's known that if method throws something, it doesn't have to be declared in the method header...

public void f(A a) { 
    System.out.println("in B"); 
    throw new java.io.IOExeption();
}
Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
student
  • 25
  • 6

1 Answers1

0

It's known that if method throws something, it doesn't have to be declared in the method header

That's only true for unchecked exceptions. Your method throws an IOException which is a checked exception so you must either catch it or declare that you throw it otherwise compilation will fail.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
  • **unchecked exceptions** never have to be declared in the method header? and is it the only reason for compiler error in the given example? – student May 11 '16 at 09:17
  • No, they don't have to be declared in the method header, and you are not obligated to surround them with try/catch. I don't see anything else that might fail compilation in your code. – Ori Lentz May 11 '16 at 09:32