0

I know, there is an implicit super() statement in the constructor of the subordinate class, but how do the class fields, instance fields, and constant fields are initiated and their order in super class and subordinate class, also where are the method information stored?

As demonstrated below, the output of the program is "null", but it will be "child" if I add the static modifier before s in the child class. I suppose that to explain such result, the answer to the questions above is essential.

public class Parent {

    private String s = "parent";

    public Parent() {
        call();
    }

    public void call() {
        System.out.println(s);
    }

    public static class Child extends Parent {
        private /*static*/ String s = "child";

        public Child() {
        }

        public void call() {
            System.out.println(s);
        }
    }
    public static void main(String[] args) {
        Child child = new Child();
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Saint
  • 1,492
  • 1
  • 11
  • 20
  • 1
    Hint: whenever you think about "basic" problems - it is pretty safe to assume that *anything* you can think of asking has been asked and answered here before ;-) – GhostCat Jul 21 '17 at 06:48

1 Answers1

0

you can create constructor with parameters like this in parent class

public Parent(String s) {
        this.s = s;
        call();
    }

and child class constructor

  public Child() {
     super(this.s);
  }

when you are declaring Child Constructor his first line is super() with default ; and it is calling Parent class's constructor and Parent class's call method.

you can also do like this

public class Parent {

    private String s = "parent";

    public Parent(String ss) {
        call(ss);
    }

    public void call(String ss) {
        System.out.println(ss);
    }

and child class

public static class Child extends Parent {
        private String s = "child";

        public Child() {
             super(this.s);
        }
    }
    public static void main(String[] args) {
        Child child = new Child();
    }
}

you don't need call() method in child class anymore because you have it in parent class and you can access this method from child class too .