Static final in supertype - java

Why is it that even if you have declared a private static final variable, a color - defaultC, let's say - then you still cannot use this.defaultC in the super constructor (i.e. you can only use super(defaultC) and not super(this.defaultC) even though it is equivalent to simply defaultC.
I was simply trying to extend a Tile class to a Wall class and the Wall class I stored all of the necessary private static final variables for all walls (such as their width and height, another int and the default color), and the Tile class already has some of the variables (but they are protected not private). I didn't want the warning Field hides another field to pop up (because there Tile.java and Wall.java have the same names for many variables), so I used this. for my private static final variables, and there were errors galore.
It's not particularly troubling (as I simply have a few warnings), but I was simply wondering why. I am guessing that the compiler simply doesn't like it because you cannot reference this before the supertype, but there are still exactly the same. Has such a feature not been added yet that overlooks such a thing or is there another reason I cannot see that you cannot use super(this.PRIVATE_STATIC_FINAL_VARIABLE);?

A static variable does not belong to any instance of an object. The this keyword should refer to an instance of an object and variables used within. While you can use the this keyword to access static variables, you should not.
Also, a variable marked private in a super class cannot be accessed within a child class.
To reference a variable declared in a super class from a child class using the this keyword, that variable must be declared protected or public.

You could try to tie the static final variable to the class you're in when passing it to super. I believe you can do this by doing something like super(SubClass.PRIVATE_STATIC_FINAL_VARIABLE);

Here we have two things to know,
what is the meaning of static keyword.
what is the meaning of this keyword
what is a constructor
in java, there are two types, class and instance of an class. We can use a class without creating an instance of it, or after creating a instance of the class itself.
object is an instance of a class.
The keyword static is used with the class. this is used with instances of class. And this keyword refers the instance of the class it is used within.
An instance of an class(object) is created after calling the class's constructor. We can use keyword this only after creating an instance of class (inside the object).
As the constructor method is called before creating the instance of the class, We can't use this keyword inside a constructor. That's why you got an error in super(this.defaultC) but not in super(defaultC)
And you can't use this keyword inside constructor for PRIVATE_STATIC_FINAL_VARIABLE as well.
But you are allowed to use PRIVATE_STATIC_FINAL_VARIABLE without using this
i.e. super(PRIVATE_STATIC_FINAL_VARIABLE)

Related

How can class name without object be used to access its contents in java?

JMenuItem print = new JMenuItem("Print");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
I'm new to java. I have learned that if we want to access the contents of class then we have to first create an object of that class. Then we can use that object to access the class's contents.
But here KeyEvent and ActionEvent are classes and they can access their fields VK_P and CTRL_MASK without the help of any object. How is this possible?
Static variables, or variables initialized with a static keyword, are able to be accessed without instantiation of a class object since they are not tied to a particular instance of the class but the actual class itself.
You can access a class's variable without via an instance of that class if that variable is static.
Static variables, or variables declared with a static keyword, are class level data members
NOT instance/object level.
This means - the same static variable is common to all instances of the class and they all can access it (!!).
public class Perrson{
public static int personCounter;
mean:
you can access personCounter as Person.personCounter++ for instance..
However, when you have Person instances p1, p2,...
p1.personCounter++
p2.personCounter++
access the same variable !
It is good for example for object counter when Person constructor advances the counter.
by yl

Java - Is it ok to instantiate class objects inside class? [duplicate]

Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.

Working with Math class without instantiating it

I am new to programming and was studying "Head First Java", I just saw a problem where there was used Math class like this
int x= Math.round(float value);
and it was mentioned we don't need to instantiate Math class because its constructor is set private. What does that mean? Until now I read we need to instantiate that class and reference variable to play around with methods and instance variables of the class how does Math class work like this?
we don't need to instantiate Math class because its Constructor is set Private
Because all the methods in Math class are static you can use the class name to invoke them. So there is no use instantiating the class , hence the constructor was declared private. it will also prevent sub classing the Math class, since it is the only constructor.
Look at the open source code :
Don't let anyone instantiate this class.
private Math() {} // only constructor defined in Math class
The methods of Math class doesn't depend on the internal state of the class , they are just like utility functions . So it was wise to declare them as static. static methods can be invoked by directly using the classname , hence no use of instantiating the class. They belong to the class, not specific objects of that class.
You can refer the JLS 8.4.3.2 :
A class method is always invoked without reference to a particular object.
The Math class have all methods as a static, and you need to get the method from the class itself. No need to create instance variable to access Static variable and methods
Refer Math Class java doc. you find all method here static i,e. Math.round
Private constructors means that they can only be called upon from within the class to which they belong, a good example of the use of private constructors can be found here Can a constructor in Java be private?
Private constructors do however have nothing to do with the fact that you can use methods from the MATH class without instantiating them. This is because the methods of MATH class are static i.e. a static method can be called upon without instantiating an object of the class to which the methods belong.
As said in the comments above, you have no use of instantiating a MATH object, therefore the constructor is private, but you could use the MATH methods anyway had the constructor been public.

Why should a variable be declared as static and final

A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere. But why should the same variable be declared as final, which will not allow the variable to be changed else where (constant value)?
static so that the variable or method can be accessed without creating a class instance, and there is only one variable for the class instead of one for each instance.
A final class cannot be extended. A final variable cannot have its value changed, it behaves as a constant. And a final method cannot be over-ridden.
The minute a variable is defined as final, it should probably not be referred to as "variable", since it no longer "varies" :)
A static variable is not tied to any particular instance of a class -- it is only tied to the class itself and only from a scoping standpoint.
So there you are -- a static and final variable is actually a value that is not tied to any particular instance of class and does not vary. It is a constant value, to be referenced from anywhere in your Java code.
At some point, when you should decide to change the value of this constant, it only takes one change to propagate this change correctly to all other classes that use this constant.
A variable declared as static means that its value is shared by all instances of this class. Declaring a variable as final gives a slightly better performance and makes your code better readable.
local variables are on the stack and are not static.
You can have a static field which may or may not be final. You would make the field final if it is not going to change.
static fields can be modified (e.g. public static fields can be modified by any class). static final fields cannot be modified after initialization.
Like you mention yourself, this is done to create constants. You create a single field to hold a value with a specific meaning. This way you don't have to declare that value everywhere, but instead you can reference the static.
Static has nothing to do with getting the latest and single copy unless "single copy" here means one and the same value for all the instances of a class (however, I think you may be confusing it with volatile). Static means class variable. You make it final when you want that to be a constant (that's actually the way Java constants are declared: static final).
static final is used in Java to express constants. Static is used to express class variables, so that there is no need to instantiate an object for that class in order to access that variable.
Final methods can't be overriden and final variables can only be initialised once.
If you only use the static keyword, that value will not be a constant as it can be initialised again.
May be to provide something similar to constants.
Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.
for example user.lastName lastName should be field because it is needed during object lifecycle
Variables should be declared as static only if they’re not required for use in more than one method of the class or if the program should not save their values between calls to the class’s methods.
for example Math.max(num1,num2) Im not intristed in num1 and num2 after compleating this operation
Final stops any classes inheriting from it
You create static final variable to make its value accessible without instantiating an object.
E.G.:
public class MyClass
{
public static final String endpoint= "http://localhost:8080/myClass":
/* ...*/
}
Then you can access to the data using this line:
MyClass.endpoint

java objects, shared variables

I have a simple question here.
If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(
usually I declare it like this :
private int number;
)
can it be used in a different object which was also made [declared] in the main class?
btw I do not care about security atm, I just want to make something work, don't care about protection)
Here's a telling quote from Java Language Specification:
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[Example program follows...]
In short, a static field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static field as a variable shared by instances of the class, but it's much more consistent to think of static fields as belonging to the class, just like static method also belongs to the class, etc.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static members through an instance instead of a type expression.
Related questions
Java - static methods best practices
Static methods
calling non-static method in static method in Java
non-static variable cannot be referenced from a static context (java)
When NOT to use the static keyword in Java?
Static variables and methods
If the class holding 'number' is called MyClass
you can refer to it as MyClass.number from any method.
Doing so for a variable is not good design though.
There are really two issues here: public vs. private in the context of inner classes, and static variables.
Part 1:
static means that you don't need an instance of the class to access that variable. Suppose you have some code like:
class MyClass {
public static String message = "Hello, World!";
}
You can access the property this way:
System.out.println(MyClass.message);
If you remove the static keyword, you would instead do:
System.out.println(new MyClass().message);
You are accessing the property in the context of an instance, which is a copy of the class created by the new keyword.
Part 2:
If you define two classes in the same java file, one of them must be an inner class. An inner class can have a static keyword, just like a property. If static, it can be used separately. If not-static, it can only be used in the context of a class instance.
Ex:
class MyClass {
public static class InnerClass {
}
}
Then you can do:
new MyClass.InnerClass();
Without the 'static', you would need:
new MyClass().new InnerClass(); //I think
If an inner class is static, it can only access static properties from the outer class. If the inner class is non-static, it can access any property. An inner class doesn't respect the rules of public, protected, or private. So the following is legal:
class MyClass {
private String message;
private class InnerClass {
public InnerClass() {
System.out.println(message);
}
}
}
If the inner class has keyword static, this would not work, since message is not static.
static variables are shared by all instances of a given class. If it's public, it is visible to everything.
non-static variables belong to only one instance.
Since your main method is static, it can only see static variables. But you should avoid working statically - make an instance of a class, and pass the data around as method/constructor parameters, rather than sharing it via static variables.

Categories

Resources