by swaranga · 4y ago · 0 comments
public static void main(String[] args) {
Parent instance = new Child();
if (instance instanceof Child p) {
instance.print(); // prints Parent
p.print(); // prints Child
}
}
static class Parent {
static void print() {
System.out.println("Parent");
}
}
static class Child extends Parent {
static void print() {
System.out.println("Child");
}
}
Hence, with flow typing, existing code could break in subtle ways. fun foo(i: Int) = ...
fun foo(n: Number) = ...
fun main() {
val n: Number = 12;
foo(n); // calls foo(Number)
if (n is Int) {
foo(n); // calls foo(Int)
}
}
It's as if smart casting causes the static type of `n` to change in different parts of the main function. As such it also seems to affect overload resolution. Maybe this is exactly what you want. On the other hand it seems like it could lead to some very subtle errors. I'm not a Kotlin programmer, so Kotlin experts please feel free to correct me on details.This is, in C#, all methods are called according to an object's apparent-type, not its actual-type, by default. To get the Java-behavior, a C#-method would need to be declared `virtual` (or `abstract`), and then more-derived methods would need to choose to `override` them (rather than hide them, often via `new`).
Part of the advantage might be performance. This is, methods that go with the apparent-type don't need to do a virtual-lookup-table resolution, which can save some work in method-calls.
Another advantage is that it can help provide more flexibility in class-hierarchies, since more-derived classes can "hide" less-derived classes' methods without overriding them. It's probably not something that folks really need to do too often, but it's nice to have an easy solution when such a case occurs.
> instance.print(); // prints Parent
why? the parent print should be shadowed/overidden by the child bruh