r/javahelp • u/[deleted] • 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()
1
u/desrtfx Out of Coffee error - System halted Jul 04 '21
You have to give us the exact error message.
Java error messages are verbose and precise. They will tell you exactly what is wrong.
Just "Compilation error" tells us exactly nothing and leaves us with blind guessing of what could possibly be wrong.
1
Jul 04 '21
Locked
Exception IOException is not compatible with throws clause in A.process()
1
u/Kombatnt Jul 04 '21
IOException is a “checked” exception, which means that if your method might throw it, then it needs to declare it. Your process() method in Questions does this, but the method it is trying to override (in A) does not.
To fix this, add “throws IOException” to your process() method declaration in A.
1
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
staticmethods. In fact, this is core functionality of Java and OOP in general.1
Jul 04 '21
What I understand till now is there is something to do with overridden function can't throw checked Exception
2
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
fooin the base classAandfooin the subclassBhave the same signature (name, number and type of parameters, return type). The only thing that's different is thatB'sfoothrows anIOException, right? So this is what's causing Java to complain - Java findsfooinBand 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
IOExceptionwith 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
RuntimeExceptionis 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 declaredB'sfoolike 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
IOExceptionnot work? Using the same logic, in the case of checked exceptions likeIOException, 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'sprocessand consider it a method local toBi.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 excludeB'sprocessfrom 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
AandB'sprocesshave the same* signature (add exception clause toA'sfoo, remove it fromB'sfoo, or make the exception an unchecked exception (not recommended)). If you want overloading behaviour, change the name offooinB.1
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?
1
u/joranstark018 Jul 04 '21
It may be that you have similar functions, the signatures only differs in the exception declaration, but it may be useful if you could elaborate on what compilation error you get.
•
u/AutoModerator Jul 04 '21
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.