java constructor order - java

This java program is easy and full of comment,so you can understand it fast.however,why in construct staff[1],the program first go to the statement:
this("Employee #" + nextId, s);
then go to the object initialization block,and then go back to the statement,how confusion.why not it first use the object initialization block
import java.util.*;
public class ConstructorTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry", 40000);
staff[1] = new Employee(60000);
staff[2] = new Employee();
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",id=" + e.getId()
+ ",salary=" + e.getSalary());
}
}
class Employee
{
// three overloaded constructors
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(double s)
{
// calls the Employee(String, double) constructor
this("Employee #" + nextId, s);
}
// the default constructor
public Employee()
{
// name initialized to ""--see below
// salary not explicitly set--initialized to 0
// id initialized in initialization block
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
private static int nextId;
private int id;
private String name = ""; // instance field initialization
private double salary;
// static initialization block
static
{
Random generator = new Random();
// set nextId to a random number between 0 and 9999
nextId = generator.nextInt(10000);
}
// object initialization block
{
id = nextId;
nextId++;
}
}

Because this("Employee #" + nextId, s); includes an implicit call to the superclass constructor, which of course must be executed before the initializer block of the subclass.
Using instance initializers is generally a bad idea as they are not well known, cannot do anything more than constructors, and mixing both leads to confusion.

This follows the order specified in section 8.8.7.1 of the JLS:
(Final two bullets)
Let C be the class being instantiated, let S be the direct superclass of C, and let i be the instance being created. The evaluation of an explicit constructor invocation proceeds as follows:
First, if the constructor invocation statement is a superclass constructor invocation,
(Snipped because it's not in our case)
Next, the constructor is invoked.
Finally, if the constructor invocation statement is a superclass constructor invocation and the constructor invocation statement completes normally, then all instance variable initializers of C and all instance initializers of C are executed. (Snip) An alternate constructor invocation does not perform this additional implicit action.
So the instance initializer is executed immediately after the superconstructor is called - which is (implicitly) from public Employee(String n, double s). This should happen before the body of that two-parameter constructor is executed.

Not sure what the actual question is, it's a bit confusing. The order of initialization (static, object, constructor) is predefined and has nothing to do with in which order they appear in the code. As for the general style, I generally discourage using object initialization blocks. It's a very common source of errors, it makes exception-handling more complex and it's hard to debug. In addition, it's not a very common pattern so developers tend to miss looking for it when analyzing bugs.

The Java compiler must ensure that the code in the object initialization block is called from each constructor. For most constructors, it does this by inserting the code into the constructor right after the implicit or explicit call to super(). For compilers that start with this(), however, first of all there is no implicit call to super() -- the other constructor handles that. Secondly, in such a constructor the object initializer block can't be inserted at all, since the code will be picked up when the second constructor is called. Therefore the this() call is the very first thing that happens.

Related

Why am I getting the error "cannot resolve method "x" in "x""?

The purpose of this program is to create a class and tester class for a select object(in my case a monitor), with at least one overloaded method. And in the client class, I have to instantiate at least three instances of the object. So far I believe I've finished the first class with the declaration of methods, getters and setters, and constructors. The problem occurs in my tester class, where I get the error "Cannot resolve method 'MonitorV82' in 'Monitor V82'. I don't know for sure why I'm getting this error, any advice?
My first class is:
public class MonitorV82
{
private double l;
private double h;
//one parameter constructor, all private instance variables initialized
public MonitorV82(double monitor1Height) {
//2.When this gets name1(jupiter), it designates "jupiter" to the variable "n"
h = monitor1Height;
l = (monitor1Height * 1.77);
}
//two parameter constructor
public MonitorV82(double monitor1Height, double monitor1Length){
//3.When this gets name1(jupiter), and a double, it sets jupiter to "n" and the diameter to "d"
h = monitor1Height;
l = monitor1Length;
}
public double getMon1height() { return h; }
public double getMon1Length() {
return l;
}
public void setMon1height(double name) { h = name; }
public void setMon1Length(double diam) {
l = diam;
}
public String monType(int resolution)
{
String monitType = "";
if (resolution == 1080) {
monitType = "lenovo";
} else if (resolution == 4000) {
monitType = "samsung";
}
return monitType;
}
//overloaded method
public String monType(int pixLength,int pixHeight)
{
String monitType = "";
if (pixHeight == 1080) {
monitType = "lenovo";
} else if (pixHeight == 4000) {
monitType = "samsung";
}
return monitType;
}
}
My tester class(where the error is) is:
public class V8Tester {
public static void main(String[] args) {
double length1 = 32.2;
double height1 = 51.8;
double length2 = 31.8;
double height2 = 50.6;
int resolution = 0;
MonitorV82 monit1 = new MonitorV82(length1);
resolution = monit1.MonitorV82(height1);
}
}
I am still learning Java in school so please don't roast me if something seems obvious or simple. Thank you for your help.
You are getting this error because there is no method MonitorV82, only a constructor. Also you are trying to instantiate the int variable resolution with a MonitorV82 object, which is not possible, because the compiler expects an int value.
If you want the resolution that refers to the pixel count of the MonitorV82 object with known pixel height, you first need to find out it's pixel length. You can do this by using your getMon1length() method and the calculate the resolution by length * height. Ultimately what I think you are trying to do is:
int heightMonit1 = monit1.getMon1height();
int resolution = (int)length1 * (int)heightMonit1;
You need to type cast, because you want to instantiate the int variable resolution with a calculation of double values.
You could however also use your second constructor and do:
MonitorV82 monit1 = new MonitorV82(length1, height1);
int resolution = (int)monit1.getMon1height() * (int)monit1.getMon1length();
Before answering the question in the title, you need the answer to this question:
What is a constructor in Java?
A constructor in Java is a special method used to "construct" (build, instantiate, etc.) objects. A constructor follows these basic rules:
The name of the constructor should match exactly the class name. In your case, MonitorV82 is this name.
A constructor doesn't have a return type. The new operator is responsible for returning a new object matching the type of the class in which the constructor is being invoked.
Knowing this, let's address the original question: Why the error? Because in MonitorV82 there is only a constructor a with matching name, but not a regular method with the same name. Consider my example below
public class Test {
private String name = "default";
// constructor #1
public Test() {}
// constructor #2
public Test(String name) {
this.name = name;
}
// method #1
public void Test() {
System.out.println(name);
}
// method #2
public void Test(String name) {
System.out.println(name);
}
}
Notice that in the code above, I have two constructors and two methods with the same name (matching case) and same parameters. This is allowed in Java although this is STRONGLY discouraged due to how confusing it can get.
What does this mean for you?
To create monit1, you need to invoke a CONSTRUCTOR. Once you construct the object, you cannot use it to invoke a constructor. You use objects to invoke non-static, accessible methods. Based on this, the line
MonitorV82 monit1 = new MonitorV82(length1);
is totally fine. However, the set resolution line is not resolution = monit1.MonitorV82(height1); because you have no METHOD named MonitorV82 (you just have a constructor with a matching name). You fix this by creating a method in your class that does exactly that. Since method names should be descriptive of their function, creating a method named setResolution or calculateResolution should be fine. What you should not do is used an ambiguous name; especially using the same name as the constructor.
Lastly, I will leave you with this small piece of advice: Just because the language allows you to do something, that does not mean that it is correct or OK to do so. My code example (along with this lengthy explanation) should've illustrated this point.
tl;dr
You asked:
Why am I getting the error "cannot resolve method "x" in "x""?
Because your last line tries to call a method named MethodV82 which does not exist on an instance of the class named MethodV82.
Details
Firstly, you should have indicated which line of code is causing that error.
You have at least one offending line, that last line. The code monit1.MonitorV82(height1) makes no sense. That code is trying to call a method named MonitorV82 on the instance named monit1. But of course there is no such method. Thus the error « Cannot resolve method ».
I cannot follow your logic, so I cannot give a fixed replacement code snippet.
I think you are misunderstanding the use of constructors.
I guess that what you want to do with your monit1.MonitorV82(height1) is to set the height of your monit1 instance to height1.
You need to call the setter to do so, not a constructor. The constructor is not known as a class method, that is why your error occurs. Use
monit1.setMon1height(height1);
Next, I think that you are trying to retrieve a resolution from your monitor, but you have no method inside of your MonitorV82 with this aim so I suggest that you create a method for this such as
public int computeResolution() {
return this.h * this.l;
}
In your test class you end up with:
public class V8Tester {
public static void main(String[] args) {
double length1 = 32.2;
double height1 = 51.8;
double length2 = 31.8;
double height2 = 50.6;
int resolution = 0;
MonitorV82 monit1 = new MonitorV82(length1);
monit1.setMon1height(height1);
resolution = monit1.computeResolution();
}
}
Edit: Even the instantiation of your monit1 does not seem correct. The only one parameter constructor you have is based on height and you are calling it with length1
Edit2: My example of computeResolution() will probably end up with an exception as I am returning an int from a compute action on doubles. But I think that it is not the main issue here

why property overriding in kotlin makes primary constructor property zero

I'm trying to pass value to constructor and print the values.
open class Car(c: Int){
open var cost: Int = c
init {
println("This comes First $cost")
}
}
open class Vehicle(cc: Int) : Car(cc) {
override var cost: Int = 20000
init {
println("This comes Second $cost")
}
fun show(){
println("cost = $cost")
}
}
fun main() {
var vehicle = Vehicle(1000)
vehicle.show()
}
Output
This comes First 0
This comes Second 20000
cost = 20000
if i just comment this line
override var cost: Int = 20000
output would be
This comes First 1000
This comes Second 1000
cost = 1000
Why super constructor cost is zero when override the property in subclass?
I need this to be compared to java concept for better explanation here
In Java to create a mutable property cost, you need to define a field cost and a getter and setter:
public class Car {
private int cost;
public Car(int c) {
this.cost = c;
System.out.println("This comes First " + getCost());
}
public int getCost() { return cost; }
public void setCost(int cost) { this.cost = cost; }
}
Kotlin has the concept of a property embedded in the language, so you can achieve the same with only creating a var property as you did:
open class Car(c : Int){
open var cost : Int = c
init {
println("This comes First $cost")
}
}
This is much more concise from the developer perspective, but the implementation is the same. Kotlin compiler is generating a field cost, a get method and set method for us under the hood.
Now the interesting part. When you make the cost property in the parent class open and overrides it in the child class, you are actually overriding the get method. It is not possible to override a field, neither in Kotlin nor Java.
As #Pawel mentioned in his answer that's the java code for the Vehicle child class:
public class Vehicle extends Car {
private int cost = 20000;
#Override
public int getCost() {
return this.cost;
}
#Override
public void setCost(int var1) {
this.cost = var1;
}
public final void show() {
System.out.println("cost = " + getCost());
}
public Vehicle(int cc) {
super(cc);
System.out.println("This comes Second " + getCost());
}
}
When you execute println("This comes First $cost") in the parent class, you are actually executing System.out.println("This comes First " + getCost()); and the actual getCost() being called is the one in the child class Vehicle. As the child class cost field has not been initialized yet, as we are still executing the super(cc) call, its value is zero.
Have you looked at generated bytecode and tried to reverse decompile it back to java? If you're confused how Kotlin works under the hood often times it can help you understand.
In this case your classes in Java would look like this (i decompiled your code and cleaned it up a little):
public class Car {
private int cost;
public int getCost() {
return this.cost;
}
public void setCost(int var1) {
this.cost = var1;
}
public Car(int c) {
this.cost = c;
System.out.println("This comes First " + getCost());
}
}
public class Vehicle extends Car {
private int cost = 20000;
public int getCost() {
return this.cost;
}
public void setCost(int var1) {
this.cost = var1;
}
public final void show() {
System.out.println("cost = " + getCost());
}
public Vehicle(int cc) {
super(cc);
System.out.println("This comes Second " + getCost());
}
}
What's happening is open var is just declaration for setter and getter which Vehicle overrides.
Remember that initialization of super class always happen before child, so when Car constructor is executed Vehicle is still not initialized (Vehicle.cost is still 0).
That means in first case:
This comes First 0 // Car constructor prints 0 because it returns Vehicle.cost which is unitialized
This comes Second 20000 // Vehicle constructor returns initialized value
cost = 20000
And in second case where you DON'T override the cost, both Car and Vehicle return Car.cost:
This comes First 1000 // Car constructor assigns constructor parameter to Car.cost and returns it
This comes Second 1000 // Vehicle constructor returns Car.cost as well
cost = 1000
Also note that in first case your constructor parameter is meaningless: it gets assigned to Car.cost but that field is inaccessible because it's shadowed by Vehicle.cost.
This behavior may not be intuitive, but it's the result of how properties work with the JVM.
When you subclass Car, the Car initialization occurs before the subclass Vehicle initialization. So the println call in Car's init block accesses the property before Vehicle is initialized. Since this access amounts to calling a getter method in Java, it is accessing the subclass's getter, not its own since it's been overridden. Since the subclass has not initialized yet at this stage, its getter returns the default value of the backing field, 0.
If you do this with a non-primitive, non-nullable property, you can "trick" Kotlin into giving you a Java NullPointerException for what can normally be assumed to be non-null.
In either case, the default code inspections should warn you about trying to access an open property during initialization, because of this unexpected kind of behavior.
The work-around would be to use a private backing property:
open class Car(c : Int){
private var _cost: Int = c
open var cost : Int
get() = _cost
set(value) { _cost = value }
init {
println("This comes First $_cost")
}
}
In simple words.
when object is created Vehicle(1000)
- first init will get called
- then variables get initialized
step 1:- it will try to call constructor of Vehicle
step 2:- since it inherited Car it will try to call constructor of Car first
step 3:- it always look for override methods not overridden methods or properties So, $cost is pointing to override property.
step 4:- override var cost : Int = 20000 is not initialized when you are printing
println("This comes First $cost") as init run first then property will initialized.
step 5:- So $cost is by default zero.
Just try this, below open var cost : Int = c
put, var costTest : Int = c. "no open keyword"
Then, on Vehicle init put,
println("This comes Second $cost $costTest")
here you will get costTest = 1000.
Its because costTest you haven't override

Why to use static in instance variable when we use "this" to call another construtor?

I have little confusion about the below code.
class TestConstructor1{
static int num,num1;
TestConstructor1(int n)
{
this(num,num1);
num=n;
System.out.println("One argument constructor");
System.out.println("Value are "+num+" and "+num1);
}
TestConstructor1(int l,int m)
{
num=l;
num1=m;
System.out.println("Two argument constructor");
System.out.println("Value are "+num+" and "+num1);
}
public static void main(String args[])
{
TestConstructor1 ts=new TestConstructor1(10);
}
};
The constructor is called the way it have to called i.e. it is calling two argument constructor first and then its own constructor but I am interested to know why we have to use static before the instance variable and why we cannot use instance variable without declaring as static.
I am waiting for your responses.Thank You...
You are a little confused about how to chain constructors. Do it like this instead:
private int num,num1; // instance values, initialized by constructors
TestConstructor1(int n)
{
this(n,0);
System.out.println("One argument constructor");
System.out.println("Value are "+num+" and "+num1);
}
TestConstructor1(int n,int m)
{
super(); // this call is implicit and does not explicitly need to be in the code
num=n;
num1=m;
System.out.println("Two argument constructor");
System.out.println("Value are "+num+" and "+num1);
}
Note that the first calls the second passing in the n argument it was given and a suitable default for the second argument.
As to passing instance variables to chained constructors... this is not possible because accessing an instance variable is implicitly a reference to this object, which is not permitted until the call to the super constructor is done, after which you can't invoke another constructor.
But the desire to pass an instance variable to this object's constructor is not logical... in essence you are saying "please initialize this object with itself"... at a point where this object is not yet initialized. It's something of a chicken and egg problem. You can't uses the object's values to initialize those values.
when you say static , it belongs to a class and not a member variable for a specific object .
if you want each instance of TestConstructor1 to have its own copy of the num and num1 then remove static.
In the first line of every Constructor, there is always a call to either super() or this(). Instance variables are set to their defaults, after this call is complete. That's why you cannot use instance variables in calls to super() or this().
You cannot pass instance members in a constructor because the instance is not initialized yet. You can only pass constants like static members which are members of the class:
public static final int DEFAULT_M = 42;
TestConstructor1(int n)
{
this(n, DEFAULT_M);
}
Also you should not call methods except they are static or private and do not access members!
We have to use static because once variables are declared as static they will get memory once only in their life time ,if you don't make them static it will get initialized again and again.

Passing arguments in main method in java class

Can someone tell me what is the need to declare a class like this:
public class Test {
String k;
public Test(String a, String b, String c){
k = a + " " + b + " " + c; //do something
}
public void run(){
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test(l,m,n);
obj.run();
}
}
Of course it works but I don't get the point why would one use such way to implement something. Is it because we need to pass arguments directly to the class main method that is why we use this way or is there some other reason?
What is the purpose of public Test(...) using the same class name. Why is it like this?
The public Test(...) is a constructor and its purpose is for object creation. This is clearly seen from the sample code...
Test obj = new Test(l,m,n);
The variable obj is instantiated with object Test by being assigned to the Test's constructor. In java, every constructor must have the exact same name (and case) as the java file it's written in (In your case constructor Test is found in Test.java).
...Why is it like this?
It all depends on what you want to do with your object. You could have a zero-argument constructor (i.e. requires no parameters) and have methods to set your l, m, n, like so:
package net;
public class Test {
private String k;
/**
*
*/
public Test() {
super();
// TODO Auto-generated constructor stub
}
public void set(String a, String b, String c) {
k = a + " " + b + " " + c; //do something
}
public void run() {
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test();
obj.set(l, m, n);
obj.run();
}
}
As you can see, it's exactly the same feature as your example but with a zero-argument constructor.
If your class has no constructor at all, java adds a public zero-argument constructor for you automatically.
Hope this helps.
The method called Test is a so-called constructor for the Test class. The constructor is the method that gets called when you write something like new Test(...).
Bear in mind that the main method is a static method, which means that it does not require an instance of the class Test to be called. This is not the case for the run method. run is an instance method, and to invoke it you need an instance of the Test class (the obj in your case).
The public Test(...) bit is the constructor of that class. It always has the same name as the class. Classes and main methods are two quite different aspects of programming. Classes define reusable components that have both state and methods. The main method is a special method that gets called from the command line.
Your example is so trivial that it doesnt really show any benefits of Object Orientated Programming. If you consider an example where you had different Classes intetracting you might get more of a feel for it.
The main method is the entry point for the program and is called when you run java Test from the command line.
public Test(String a, String b, String c) is a public constructor for the Test class and is called when you call new Test(l,m,n); Note that a in the constructor and l in main method refer to the same String... this also applies to b and m; c and n.
As a side note, this class expects to be passed three values from the command line, and then stores them in l, m, and n
One last note: If you have a method with the signature public void run(), your class should likely implement Runnable so that it can be used in a Thread.
Learn Java.
A constructor is a function that gets called to create an object, and it's denoted by a function with the same name as the class, but no return type. Multiple constructors can be declared with different arguments.
In this case, the arguments are taken out of the argument array and passed as arguments to the constructor for Test.
These are fundamentally basic concepts to the Java programming language. You should read up on Java. Try Thinking in Java, this is a great book to get started.

What happens when subclasses don't define a constructor in Java?

I have a few cases I wonder about. First, if you have no constructor:
class NoCons { int x; }
When I do new NoCons(), the default constructor gets called. What does it do exactly? Does it set x to 0, or does that happen elsewhere?
What if I have this situation:
class NoCons2 extends NoCons { int y; }
What happens when I call new NoCons2()? Does NoCons's default constructor get called, and then NoCons2's constructor? Do they each set the respective x and y fields to 0?
What about this version:
class Cons2 extends NoCons { int y; public Cons2() {} }
Now I have a constructor, but it doesn't call the super class's constructor. How does x ever get initialized? What if I had this situation:
class Cons { int x; public Cons() {} }
class NoCons2 extends Cons { int y; }
Will the Cons constructor be called?
I could just try all these examples, but I can't tell when a default constructor is run. What's a general way to think about this so that I'll know what happens in future situations?
When a Java class has no constructor explicitly defined a public no-args default constructor is added so:
class Cons { int x; }
is equivalent to:
class Cons { int x; public Cons() {} }
A subclass's constructor that doesn't explicitly define which of its parent's constructor it calls will automatically call the default constructor in the parent class before it does anything else. So assuming:
class A { public A() { System.out.println("A"); } }
then this:
class B extends A { public B() { System.out.println("B"); } }
is exactly equivalent to:
class B extends A { public B() { super(); System.out.println("B"); } }
and the output in both cases will be:
A
B
So when you do:
new NoCons2();
The order is:
NoCons's default constructor called, although this is technically the first part of (2); and then
NoCons2's default constructor called.
You want to refer to the Java Language Specification section 12.5 Creation of New Class Instances to get the official rules of object creation. The relevant section is:
Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:
Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type.)
Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.
So in your examples, when no constructor is supplied in your class definition, the default one is inserted for you. When you write
new NoCons2();
First the super constructor is called (a call to super() is inserted for you because you don't make the call explicitly).
Instance variables for the class being constructed are initialized.
The rest of the constructor body is executed (nothing in your case).
In your first example, x will be set during the construction of NoCons and y will be set during the construction of NoCons2.
So the exact sequence of events in that example will be something like:
NoCons2 constructor called.
Call to super(), goto 3
NoCons constructor called.
Call to super(), which is an implicit call to Object().
Whatever happens in Object constructor.
x is set to 0.
finish body of NoCons constructor, return control back to NoCons2 constructor.
y is set to 0.
finish body of NoCons2 constructor
NoCons2 object construction complete.
cletus answered the biggest of the questions. The answer to the other is that member variables in Java are initialized to 0, null or false (depending on the type).
Here is essentially what happens when "new" is called:
the memory is allocated (enough to hold all of the data members of the class, and all of the parent classes, and some housekeeping information)
the allocated memory is set to zero (which means 0, 0.0, false, null depending in the type)
the constructor is called for the class that is after "new" is called.
more things happen (coming after the next part)
If you do not provide a constructor the compiler does the following:
creates a no-argument constructor
the created constructor has the same access as the class (so public or package)
super() is called.
So when the constructor of the class after the "new" is called the very first thing it does is call "super()" which calls the parent constructor. This happens all the way up to java.lang.Object.
Before the body of the constructor is run the VM does the following:
the instance variables that are assigned values are given them
then the instance initializer block, if present is run.
The following code shows all of this:
public class Main
{
private Main()
{
}
public static void main(final String[] args)
{
final Foo fooA;
final Foo fooB;
fooA = new Foo(7);
System.out.println("---------------------");
fooB = new Foo(42);
}
}
class Bar
{
protected int valueA = getValue("valueA", 1);
protected int valueB;
static
{
System.out.println("static block for Bar happens only one time");
}
{
System.out.println("instance block for Bar happens one time for each new Bar");
System.out.println("valueA = " + valueA);
System.out.println("valueB = " + valueB);
}
Bar()
{
super(); // compiler adds this - you would not type it in
System.out.println("running Bar()");
System.out.println("valueA = " + valueA);
System.out.println("valueB = " + valueB);
valueB = getValue("valueB", 2);
}
protected static int getValue(final String name, final int val)
{
System.out.println("setting " + name + " to " + val);
return (val);
}
}
class Foo
extends Bar
{
protected int valueC = getValue("valueC", 1);
protected int valueD;
static
{
System.out.println("static block for Foo happens only one time");
}
{
System.out.println("instance block for Foo happens one time for each new Foo");
System.out.println("valueC = " + valueC);
System.out.println("valueD = " + valueD);
}
Foo(final int val)
{
super(); // compiler adds this - you would not type it in
System.out.println("running Foo(int)");
System.out.println("valueC = " + valueC);
System.out.println("valueD = " + valueD);
valueD = getValue("valueD", val);
}
}

Categories