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?

Advertisements

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: