Java: calling methods from constructors

There’s a Java program:

public class Constructors {
    private static class Parent {
        public Parent() {
            test();
        }

        public void test() {
            System.out.println("Hello from Parent");
        }
    }

    private static class Child extends Parent {
        private String name;

        public Child() {
            name = "Hi";
        }

        @Override
        public void test() {
            System.out.println("Hello from child " + name);
        }
    }

    public static void main(String[] args) {
        new Child();
    }
}

What does it print?
The answer is obvious if you compile and run it? Can you answer it without running?

5 Responses to “Java: calling methods from constructors”

  1. Alexey Petrenko Says:

    This code would not compile 🙂

  2. C++: calling methods from constructors « Programming is my life Says:

    […] and a half months ago I posted a question on Java. Now it’s time for its counterpart in […]


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.