CallNotStaticallyChecked
Given a type C
that does not have a method m()
,
and a reference o
of type C
,
the compiler will compile a call like o.m()
.
A method invocation on a reference of a type that does not have that method won't compile
A method invocation on a reference of a type that does not have that method will compile
CorrectionHere is what's right.
Java is a statically-typed language, where the compiler ensures (before runtime) that all method calls at runtime will succeed. Thus, it reports errors for any method call site for which it cannot guarantee this.
For polymorphic call sites this means that the compiler requires that the type of the reference on which the method is called does provide the called method (either as an abstract or a concrete method).
The following example illustrates a call site for which the compiler cannot provide that guarantee, and which as a consequence will not compile:
public class C {
}
public class Sub extends C {
public void m() { /* implementation */ }
}
public class Test {
public void bad() {
C c = new Sub();
c.m(); // this will NOT compile (type C does not provide m())
}
}
The following example shows a call site that compiles:
public class C {
public void m() { /* implementation */ }
}
public class Test {
public void good() {
C c = new C();
c.m(); // this will compile (type C implements m())
}
}
The following example shows a call site that compiles,
because class C
promises that all concrete subclasses
will implement m()
:
public abstract class C {
// promise that all concrete subclasses will provide m
public abstract void m();
}
public class Sub {
public abstract void m() { /* implementation */ }
}
public class Test {
public void good() {
C c = new Sub();
c.m(); // this will compile (type C promises m())
}
}
OriginWhere could this misconception come from?
Students with prior familiarity with dynamically-typed languages (like Python, JavaScript, or Smalltalk) may be particularly prone to this misconception.
ValueHow can you build on this misconception?
This provides an opportunity to explain the difference between dynamically and statically typed languages, and to discuss the advantages of static typing.