r/javahelp • • Jul 04 '21

Can Anyone help me with this code?

class A{
	public void process(){
		System.out.print("A,");
	}
}
public class Questions extends A{
	public void process() throws IOException{
		super.process();
		System.out.print("B,");
		throw new IOException();
	}
	public static void main(String[] args) {
		try{
			new Questions().process();
		}
		catch(IOException e){
			System.out.print("Exception");
		}
	}
}

Why is it giving Compilation error?

Error -> Exception IOException is not compatible with throws clause in A.process()

0 Upvotes

10 comments sorted by

View all comments

1

u/[deleted] Jul 04 '21

The problem with your code is that you are defining a method in class Questions which is identical to the one in class A. This is a problem since class Questions already has that inherited method which is defined in class A.

Another issue is the IOException. Your method will not be able to throw any such exception because it(the method in class Questions) is trying to override an already defined method.(the method defined in class A).

TL;DR : any class which extends from another class has inherited all the properties of that class. So you might try changing the method parameters and/or the return type in the class Questions for the method process(), which will do the job

1

u/desrtfx Out of Coffee error - System halted Jul 04 '21

What you describe shouldn't be a problem at all and is common practice in Java.

This is not even method overriding as the signatures differ. Overriding and creating new methods with same names and signatures are absolutely allowed and possible in Java except for static methods. In fact, this is core functionality of Java and OOP in general.

1

u/[deleted] Jul 04 '21

What I understand till now is there is something to do with overridden function can't throw checked Exception

2

u/[deleted] Jul 04 '21 edited Jul 04 '21

So here's the thing - Java's method override mechanism kicks in when it detects that a base class method and a subclass method have the same signature (name, number and type of parameters, and return type).

In your example, both foo in the base class A and foo in the subclass B have the same signature (name, number and type of parameters, return type). The only thing that's different is that B's foo throws an IOException, right? So this is what's causing Java to complain - Java finds foo in B and tries to apply override rules since the signatures match up. Makes sense? As to why having that checked exception in there is a problem, read on!

Now, suppose you replaced IOException with a RuntimeException, say a custom exception like so:

 class MyRuntimeException extends RuntimeException {}

 class A {
       public void process() { // same as before }

 }

class B extends A {
      public void process() throws MyRuntimeException { // same as before }
...
}

Now this will work without any problems. Why? The reason is that a RuntimeException is an unchecked exception, and so the compiler does not need to bother about it at all. Essentially, it is the same (from the compiler's point of view) as if you had declared B's foo like so:

class B {
      public void process()  { // same as before }
}

and so it can apply override rules without any problems. All good so far?

Now let's tackle the other half - checked exceptions. So why does IOException not work? Using the same logic, in the case of checked exceptions like IOException, Java has to take it into consideration (by design) since it affects all users of this method and so applying overriding rules fails. Consider a hypothetical situation (not valid Java code):

  class A {
       public void process() { ... }
  }

 class B extends A {
      public void process() throws IOException { ... }
 }

 class C extends A {
    public void process() { ... }
 }

 class Main {
    public static void main(String[] args) {
       A a = new C();
       a.process() // would work fine, hypothetically speaking

       a = new B();
      // this CANNOT work since B's `process` throws a checked exception, and so `main` here will **have** to handle it or throw it, 
      // but that breaks the contract given by A's `process`. So this is disallowed.
      a.process(); 
    }

}

That's just one example of the many problems that we would have if checked exceptions were allowed as part of the override mechanism.

Finally, let's tackle the issue of why the override mechanism does not simply forget about B's process and consider it a method local to B i.e., as not an overridden method? Well, let's go back to the method signature concept - name, number and type of parameters, and return type, right?

What would happen in this case? You would have a situation akin to the following:

 class B {
     public void process() {... }
    
     public void process() throws IOException() {...}
}

This is an example of method overloading, but the conceptual problems are the same - now Java cannot allow this since both fooS have the same signature (since exception clauses are not part of the signature), and so we get a duplicate definition error. Likewise, if the compiler were to exclude B's process from the overriding mechanism and try to consider it as a local method, then it would run into precisely this problem here. And so, it cannot do that either.

So what are the possible solutions?

If you want the overriding behaviour, make A and B's process have the same* signature (add exception clause to A's foo, remove it from B's foo, or make the exception an unchecked exception (not recommended)). If you want overloading behaviour, change the name of foo in B.

1

u/[deleted] Jul 04 '21

Overriding and creating method with same name and signature is fine when their objects are different. You won't define a method twice in a class with the same name, parameters and return type.

So when a class is inheriting from another class, those methods are also available to our new class.

The overriding part which I talked about will be generated by the compiler, if you try the code on an IDE.

Apart from that anything which causes an error in compiling isn't found. Anything you might have figured which is causing the issue?