Jtest logo




Contents  Previous  Next  Index

MISC.CTOR


Use care when calling non-"final" methods from constructors

Description

This rule flags code that calls a non-"final" method from a constructor.

The purpose of the constructor is to initialize an object. It might call some methods of its class. If it calls a non-"final" method, a derived class can override the method, depending upon how the overridden method is coded. This can lead to unexpected results.

Example

 package MISC;
 public class CTOR {
     public CTOR() {
         _size = readSize(); // violation, it can be overridden by 
 // CTOR's derived class
     }
     public int readSize() {
         return fis.read();
     }
     private FileInputStream fis = new FileInputStream ("data.out");
     private int _size;
 }

Repair

If a constructor needs to call a method for an initialization, make this method final, or private. Or, if a method is the part of some package, create a private void init() method to do all the initialization.

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp.238 - 240.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft