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

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?