-1

I have below parent class :-

class Parent {
    Parent() {
        System.out.print("Parent ");
    }
}

class Child extends Parent {
    Child() {
        System.out.print("Child");
    }
}

So when i execute Child c = new Child();

My output should be "Child" Not "Parent Child"

can we do that using reflection API?

Requirement :- I have a long Junit Setup hierarchy Which I want to avoid for some of the classes

Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25

1 Answers1

-1

What happens is when you create the Child class the Parent's class constructor is called first and then the Child's constructor.

What you could do if you must change what happens in the parent constructor is that you extract the related code into a protected method and this way you can override it in the Child class However it is error prone and not recommended (What's wrong with overridable method calls in constructors?)

class Parent {
    Parent() {
       overridableInit();
    }
    protected void overridableInit() {
        System.out.print("Parent ");
    }
}

//If you want to extend the behavior:
class Child1 extends Parent {

    @Override
    protected void overridableInit() {
        super.overridableInit();
        System.out.print("Child1 ");
    }
}

//If you want to skip the Parent behavior:
class Child2 extends Parent {
    @Override
    protected void overridableInit() {
        System.out.print("Child2 ");
    }
}
aussie
  • 119
  • 5
  • "_You could extract the text into a field and override_" - one cannot override fields. – Boris the Spider May 07 '18 at 08:05
  • "You could extract the text into a field and override its value" - to be specific. But yes i didn't us the right words. – aussie May 07 '18 at 08:09
  • 1
    The usage of the word "override" is wrong when related to fields, reword your answer and perhaps provide an example. In any case, the OP cannot change the `Parent` so this answer is not relevant. – Boris the Spider May 07 '18 at 08:21