0

Netbeans is giving me a ton of warnings about

Overridable method all in constructor

and I have read up on why overridable method calls in constructors are not recommended. But the methods I have in the constructor at the moment are purely getters for the classes members.

So in this case, when the override-able methods are purely getters is it alright to have them in the constructor? As I see it, I don't have much of an option, I need to initialize these variables in the constructor. I could create a private method like CustomInitComponents, put my variable setting code in that and call it from the constructor... would that be considered better practice?

TylerH
  • 20,799
  • 66
  • 75
  • 101
csss
  • 1,937
  • 2
  • 14
  • 24

2 Answers2

2

Are they getters or setters? Because at the end of your question you write about "initialize these variables", not retrieving their value.

In any case you can either set and get them directly (derived.x = ... or ... = derived.x) or you can have a super constructor to initialize them without caring about calling overridden methods.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • I am getting them because I am actually setting properties on them, eg. I need am setting the text in a JLabel with this.getMyLabel().setText() – csss Mar 24 '12 at 14:13
  • Quote from the tutorial - http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html - "Normally, you would put code to initialize an instance variable in a constructor." If you followed normal procedure, you would already have a handle to all instance variables without needing a getter method. – emory Mar 24 '12 at 14:46
2

No, especially getters may cause problems in constructors, since the fields they return might not be initialized yet.

Example:

abstract class A {
  public A() {
    System.out.println(getName());
  }

  public abstract String getName();
}

class B extends A {
  private String name;

  public B (String n) {
    name = n;
  }

  @Override
  public String getName() {
    return name;
  }
}

In this case, the constructor of A would run first and call getName(). However, since the constructor of B hasn't been executed yet, the field name will still be null and thus the getter would not return the correct value.

Besides that, why exactly are you overriding the getters?

Thomas
  • 87,414
  • 12
  • 119
  • 157