Skip to content

Instantly share code, notes, and snippets.

@CC007
Created October 5, 2023 23:08
Show Gist options
  • Save CC007/768973376ce4ebbfdd3482c5f1bf90b9 to your computer and use it in GitHub Desktop.
Save CC007/768973376ce4ebbfdd3482c5f1bf90b9 to your computer and use it in GitHub Desktop.
Question regarding overriding methods with sealed class/interface parameters
public class Main {
public static void main(String[] args) {
// These are objects of the only 2 classes that implement Parent
// `sealed` defines that there can't be any other classes that implement Parent
Child1 child1 = new Child1();
Child2 child2 = new Child2();
// I can call myMethod(child1) and myMethod(child2) on myClass
MyInterface myClass = new MyClass();
myClass.myMethod(child1);
myClass.myMethod(child2);
// I can also call myMethod(child1) and myMethod(child2) on myInterface
MyInterface myInterface = new MyClass();
myInterface.myMethod(child1);
myInterface.myMethod(child2);
}
}
sealed interface Parent {}
record Child1() implements Parent {}
record Child2() implements Parent {}
interface MyInterface {
void myMethod(Parent parent);
}
// Why can't I override myMethod(Parent parent) with myMethod(Child1 child1) and myMethod(Child2 child2)?
// This should be exhaustive, since Parent is sealed and there can't be any other classes that implement Parent
class MyClass implements MyInterface {
//@Override
public void myMethod(Child1 child1) {
System.out.println("Child1");
}
//@Override
public void myMethod(Child2 child2) {
System.out.println("Child2");
}
// Why is this method needed after declaring the two methods above?
@Override
public void myMethod(Parent parent) {
if (parent instanceof Child1) {
myMethod((Child1) parent);
} else if (parent instanceof Child2) {
myMethod((Child2) parent);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment