2

If i have the following scenario:

public class Foo extends Baz{
  private String banana = "banana";
  //blah blah blah
}


public class Baz{
  protected static String apple = "apple"; 
}

Which get created first, apple or banana? I want to say apple gets created first, but I am not sure.

2
  • Did you mean apple to be a static variable rather than an instance variable, or not? Commented Jul 10, 2012 at 17:26
  • The specs are quite clear about this one. Commented Jul 10, 2012 at 18:08

5 Answers 5

8

apple is created first. It is static, and in the parent level class.

The static initializer (which initializes the apple variable) will run as soon as the Baz class is loaded which will have to happen before an instance of Baz can be created.

The intsance initializer (which initializes the banana variable) will run as soon as an instance of Foo is created.

Sign up to request clarification or add additional context in comments.

Comments

4

apple is a static variable, so it's initialized at class initialization time. That occurs before an instances can be created - so it's initialized before banana in this particular case.

If apple were an instance variable, it would still be initialized before banana: instance variables are initialized as if the initializers occur at the start of the constructor body, but after any chaining to a superclass constructor. (In case you're interested, this is different to C#, where the instance variable initializers are executed before constructor chaining.)

Comments

2

To create an instance of a class, you need this class to be loaded and initialized, so obviously, the static fields will be initialized before the first instance field can be initialized.

Comments

0

As said before, apple is created first and then banana is created. You can read why this occurs in the java language specification, Chapter 12. Execution:

Comments

0

You have given clearly Baz is the parent class and Foo is extending Baz. So when ever the class initialized the parent class variables will initialize. That too the apple is static variable.

When ever the Static varibles will be initialized before the instance varibles. If those are not initialized it will take as default value for int as '0'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.