silenceislife silenceislife - 3 months ago 8
Java Question

Inheritance order - Java OOP

I'm trying to figure out the way by which Java chooses which constructor to use in a specific case. My code currently has a main class and a client, both for the purpose of testing and learning about the way classes work in Java.

public class Console {
public static void main(String[] args){
ClassTest T1 = new ClassTest();
System.out.println("Level 1 is " + ClassTest.level1);
}
}

class ClassTest {
static double level1;
ClassTest(){
double level1 = 5;
}
}


Output:


Level 1 is 0.0


Questions:


  1. Why did Java take level 1 to be 0.0, and not 5.0 as anticipated? How do I make my code such that Java outputs 5.0?

  2. Initially, my code had a minor difference from the above. These two lines were different:




System.out.println("Level 1 is " + ClassTest.level1);


was


System.out.println("Level 1 is " + T1.level1);


Both produced the same output as above. However, when I used T1 I did not have to declare level 1 as static, i.e. I just had:


double level1;


So what does the T1 code do? Eclipse filled this in automatically for me and it negates the creation of a static variable for my case.

Answer

Your code has many errors and misunderstanding of basic concepts like local vs field, instance vs static... I'll stick strictly to your questions but I recommend you read Oracle's tutorials and/or a good introduction book about Java.

Why did Java take level 1 to be 0.0, and not 5.0 as anticipated? How do I make my code such that Java outputs 5.0?

Because your code double level1 = 5; is not setting the static field. You're declaring a local variable inside the constructor and setting it to 5. If you want to set the static field in the constructor (which is a very bad design idea) you can write level1 = 5;. Ideally, you should remove static from static double level1; and put private instead.

private double level1;

So what does static do?

Static defines a field as class-wide, meaning all instances from this class will have the same value. If you change this field value, it will change on all other instances as well. More details about what static is for here.

Comments