GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Non-final method invocation in constructor — CodeQL query help documentation

Non-final method invocation in constructor¶

ID: java/non-final-call-in-constructor
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - logic
Query suites:
   - java-code-quality.qls
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

If a constructor calls a method that is overridden in a subclass, it can cause the overriding method in the subclass to be called before the subclass has been initialized. This can lead to unexpected results.

Recommendation¶

Do not call a non-final method from within a constructor if that method could be overridden in a subclass.

Example¶

In the following example, executing new Sub("test") results in a NullPointerException. This is because the subclass constructor implicitly calls the superclass constructor, which in turn calls the overridden init method before the field s is initialized in the subclass constructor.

public class Super {
	public Super() {
		init();
	}
	
	public void init() {
	}
}

public class Sub extends Super {
	String s;
	int length;

	public Sub(String s) {
		this.s = s==null ? "" : s;
	}
	
	@Override
	public void init() {
		length = s.length();
	}
}

To avoid this problem:

  • The init method in the super constructor should be made final or private.

  • The initialization that is performed in the overridden init method in the subclass can be moved to the subclass constructor itself, or delegated to a separate final or private method that is called from within the subclass constructor.

References¶

  • J. Bloch, Effective Java (second edition), pp. 89–90. Addison-Wesley, 2008.

  • The Java Tutorials: Writing Final Classes and Methods.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.