-1

Let's say I have a class

public class Child {
    public Child(Object arg1) {
        super(arg1);
    }
}

and I have a parent class

public class Parent {
    Object object;
    public Parent(Object arg1) {
        this.object=arg1;
    }
}

So my question is which would be a better coding practice

  1. Inserting the argument in the child and then passing it over to the parent

OR

  1. Inserting the argument in the parent itself without going through the child.

For clarity's sake let's say currently the child does not need the argument.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
Bhagyashree Jog
  • 90
  • 3
  • 12

3 Answers3

1

Definitely number 2 if the Child doesn't need it. That is based on having Child extends Parent.

However, if Child really doesn't need it, then you should probably have it as a private field, and set it through a public constructor, else why initialize this variable through the Child ?

abdelrahman-sinno
  • 1,157
  • 1
  • 12
  • 33
0

There is no meaning of talking this single post here. In your case, the Object of Parent is default. If it's private and you want to initialize the Object of Parent, you have to call super(arg1) in Child(Object arg1). If the access permission of Object of Parent is public or protected which means Parent allows Child to access Object, then super.object or super(arg1) have no difference here. So, maybe you need to tell the difference of access permissions like protected public private and default, check here.

Community
  • 1
  • 1
SilentKnight
  • 13,761
  • 19
  • 49
  • 78
0

By the looks of your code, calling super will result to an error, you need to extend your Child to the parent ie.

    public class Child extends Parent{
...
   }

Since you created a constructor for the parent:

public Parent(Object arg1)

the no-arguement constructor is gone by default. If the Parent needs this object how else will you then initialize the Parent when you create the Child?

  public Child() {
    super(); //ERROR
  }

super() now won't work cause you created constructor for the parent with a parameter. super is looking for Parent() without any arguements

mel3kings
  • 8,857
  • 3
  • 60
  • 68
  • Yes, Sorry missed putting Child extends Parent in the code snippet. Parent and Child are concrete classes – Bhagyashree Jog Apr 17 '15 at 09:15
  • @BhagyashreeJog - yes concrete classes but parent does not have the no constructor arguement, still need this. if Child doesnt need and parent needs, when you initialize the child, you would have to call the setter of the parent just to set the object. – mel3kings Apr 17 '15 at 09:17