Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance variable creation in java

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.

like image 241
nook Avatar asked Mar 05 '26 08:03

nook


1 Answers

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.

like image 174
nicholas.hauschild Avatar answered Mar 07 '26 21:03

nicholas.hauschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!