Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

A constructor in the base class can reference uninitialized fields or potentially cause other damage while calling an overridable method. This is because, it is possible for the wrong version (in a sub class) of the method to get invoked.

Noncompliant Code Example

This noncompliant example invokes the doLogic method from the constructor. The super class method is invoked on the first call, however, the overriding method is invoked on the second one. The issue is that the constructor for SubClass is not invoked which leaves the value of color as null.

Code Block
bgColor#FFcccc
class BaseClass {
  public BaseClass() {
    doLogic();
  }
	
  public void doLogic() {
    System.out.println("This is super-class!");
  }	
}

class SubClass extends BaseClass {
  private String color = null;
  public SubClass() {
    super();	
    color = "Red";
  }
	
  public void doLogic() {
    System.out.println("This is sub-class! The color is :" + color); //color becomes null
    //other operations
  }
}

public class Overridable {
  public static void main(String[] args) {
    BaseClass bc = new BaseClass(); //prints "This is super-class!"
    BaseClass sc = new SubClass();  //prints "This is sub-class! The color is :null"		
  }
}

Compliant Solution

This compliant solution declares the doLogic method as final so that it is no longer overridable.

Code Block
bgColor#ccccff
class BaseClass {
  public BaseClass() {
    doLogic();
  }
	
  public final void doLogic() {
    System.out.println("This is super-class!");
  }	
}

Risk Assessment

Allowing a constructor to call overridable methods may give an attacker access to this before an object is fully initialized which, in turn, could lead to a vulnerability.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET32-J

medium

probable

medium

P8

L2

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 8, Classes|http://java.sun.com/docs/books/jls/third_edition/html/classes.html]
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 4-3 Prevent constructors from calling methods that can be overridden


MET31-J. Ensure that hashCode() is overridden when equals() is overridden      09. Methods (MET)      10. Exceptional Behavior (EXC)