Ozgur Bagci
Ozgur Bagci

Reputation: 848

Running a Method in Constructor

I am a newbie. So, I couldn't find the exact words to explain what I want to do. I will try to explain.

I created a class that extends some base class. In the base class I have some methods using the object specific information to run. I mean that we defined with a constructor.

So, in the class that extends my base class, I created a constructor with super, can I call some base class method in constructor in order to run automatically after object creation.

Like that:

class Base {
    String someInfo;

    Base(String someInfo) {
        this.someInfo = someInfo;
    }

    String someMethod() {
        return someInfo;
    }
}

class MClass extends Base {

    MClass(String someInfo) {
        super(someInfo);
        someMethod();
    }
}

Upvotes: 1

Views: 833

Answers (1)

Pavel Uvarov
Pavel Uvarov

Reputation: 1100

Your question is more about theory, not practice.

In practice - you can. But you shouldn't do such things. It's about code smell and possibility for hard-to-find bugs. Look at this sample

class Base {
  private final String t;
  private final int length;
  Base(String t) {
    this.t = t;
    length = this.t.length();// here you'll got NullPointerException
  }
}
class Override {
   Override() {
     super(calculate());
   }
   String calculate() {
     return "Override";
   }
}
class OverrideB {
  private final String b = "some string";
  OverrideB() {
  }
  String calculate() {
    return b;
  }
}

In current sample when you'll try to create OverrideB instance you'll got NullPointerException - because b isn't instantiated at current moment (you can check it by yourself - it is about order of constructors calls). But you have to options to avoid this problem:

  • private methods (they cannot be overridden, only hidden in sub classes)
  • final methods (same case as for private, but they can't be even hidden and they available for all subclasses)

PS according to class names conventions you should name your mClass as MClass.

Upvotes: 1

Related Questions