This question already has answers here:
Are static variables inherited
(4 answers)
Closed 4 years ago.
I am learning interfaces in java and the source from which i am learning clearly says that static variables do not get inherited. But for some reason, I am able to access that static variable without adding the interface name before it. I want to know why is this happening and an in depth explanation of whats going on !!!? plzz help
class StaticMethods {
public static void main(String [] com) {
TourClient t = new TourClient(); // i made this a class variable in place of interface variable just for demonstration
t.check();
}
}
interface Tour {
///This stuff is just for display, doesn't play a role
static float minimalCost = 50000;
static float maximumCost = 1000000;
static float recommendedRating = 3.9f;
static int minimumVisitingPlaces = 4;
}
interface DubaiTour extends Tour {
static float Rating = 4.4f;
}
class TourClient implements DubaiTour{
void check() {
System.out.println(Rating); // This is not giving me any errors!!
}
}
NOTE :- I found a stack overflow page Does static variable inherited?
, but this does not explain in depth why is this happening, which doesn't help me
Static variables are inherited.
Once again - static variables are inherited - BUT you shouldn't use them. The reason why is, if you build your program. For optimization, your TourClient class variables get substituted with the constants. The line System.out.println(Rating) gets replaced with System.out.println(4.4) - all is well. If you edit your interface and change a variable to, say, 5.5, it won't get updated in your TourClient class. It will probably still print 4.4. When you use static variables in an interface, you need to recompile EVERYTHING. Not just the files you change.
Related
This question already has answers here:
non static variable name cannot be referenced from a static context [duplicate]
(5 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I am trying to learn java. currently learning about types of variables.
i have written a small program defining instance,local,static variables and trying to print the same from with in the main method. but i am getting error saying "non static variable i cannot be referenced from static context. Below is my program
public class variable{
int i=5;
static int j=10;
public static void main(String[] args){
int k=15;
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
Please let me know whats wrong with the program
You need to create a instance of variable and access i
variable v = new variable();
// then access v.i
BTW use Camelcase for you class name.
int i should be static becasue static context cant refer to the non-static variable
Options:
Make a new instance of your class so you can reach i. In fact it is maybe not the best option, because you should make it private, and add a getter method... :)
OR
You could change int i to static int i, because of the static main method.
+1 : it is better to have classnames camescased... :)
This question already has answers here:
What is an initialization block?
(10 answers)
Closed 7 years ago.
I read that an initializer block is "an unnamed code block that contains th code that initializes the class?
For example :
class A {
final int x;
final int y;
final String n;
{
x = 10;
y = 20;
}
public A(String name ) {
/* etc... etc */
I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?
thanks
I think it can sometimes be helpful to initialize a variable immediately when it is defined.
public class Stooges {
private ArrayList<String> stooges = new ArrayList<>();
{ stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }
// ... etc. other methods.
}
That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!
There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.
A common use for this is the static initializer block:
class A {
static boolean verbose;
final int x;
final int y;
final String n;
static {
verbose = doSomethingToGetThisValue();
}
public A(String name ) {
/* etc... etc */
This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).
See also this SO answer.
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
Hi I have this piece of code and i am really confused to why i have to make the lel method static.The error is this "non static method cant be referred from static content". Usually when I create methods either to construct new objects or to manipulate objects in the main method I do not get this error message.Plus, i never declared e to be static!!. can someone please explain to me why this occurring?? Thank you :)
class x {
public static void main(String[]args){
int e= 2232;
e= lel(e);
}
int lel(int k){
return k+1;
}
}
There are two solutions you could implement. The first option is to make your int lel(int k) a static method which would look like static int lel(int k)
Your other option is to declare a new object of your class x and use that for your lel method within main as MickMnemonic suggested in the comments. That code would look like:
e = new x().lel(e);
I believe the simplest thing would be to make the lel method static but it is up to you.
A deeper explanation of static methods can be found here.
Why should a static method in java accept only final or non final variables within its method, but not static?
For example I have the following method:
public static void myfunc(int somethig)
{
int a=10;
final int b=20;
static int c=30; //gives Error why?
}
The question is: why not?
Consider this: what would a static local variable mean?
I suggest that the only sensible meaning would be that this:
public class Foo {
static int bar = 21;
public void foo() {
static int bar = 42; // static local
return bar;
}
}
is equivalent to this:
public class Foo {
static int bar = 21;
private static foo$bar = 42; // equivalent to static local
public void foo() {
return bar;
}
}
In other words, (hypothetical) static locals would be equivalent to regular static attributes with slightly different visibility rules.
The Java language designers probably considered this, and decided that static locals added so little of real value that they were not worth including in the language. (Certainly, that's the way I would have voted.)
In Java (in Object Oriented Programming in general), objects carry state. Methods should share state through objects attributes, not through static local variables.
You can't have static local variable. It doesn't really make sense.
However you can have a static field in your class.
Resources :
JLS - Local Variable Declaration Statements
You can not have a static variable. There is no such thing. You can have a class variable as static instead.
Since every function in java has to be inside a class, you can get the same effect by declaring fields in your class. It's the simplest way, and java language designers are very conservative. They'd never add a feature like that, when there's a more obvious and less complex way to do the same thing.
EDIT: I guess philosophically functions aren't first class in java. They're not supposed to store data. Classes are, and they do.
This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Closed 4 years ago.
I've read Statics in Java are not inherited. I've a small program below which compiles and produces 2 2 as output when run. From the program it looks like k (a static variable) is being inherited !! What am I doing wrong?
class Super
{
int i =1;
static int k = 2;
public static void print()
{
System.out.println(k);
}
}
class Sub extends Super
{
public void show()
{
// I was expecting compile error here. But it works !!
System.out.println(" k : " + k);
}
public static void main(String []args)
{
Sub m =new Sub();
m.show();
print();
}
}
The scope in which names are looked up in includes the super class.
The name print is not found in Sub so is resolved in the Super.
When the compiler generates bytecode, the call will be made to Super.print, rather than a call on a method in Sub.
Similarly the k is visible in the sub-class without qualifying it.
There is no polymorphism here, only inheritance of the contents of a name space. Static methods and all fields do not have polymorphic dispatch in Java, so can only be hidden by sub-classes, not overridden. The post you link to in your comments is using 'inheritance' in a somewhat unconventional way, mixing it up with polymorphism. You can have polymorphism without inheritance and inheritance without polymorphism.
Sub extends Super so it can see all the public/protected/package (static) members of Super.
I guess this is what you described as "Statics in Java are not inherited"
change
static int k = 2;
to
private static int k = 2;
and your Sub program won't see 'k' anymore and won't compile;
also try to create a new 'static int k=3;' in Sub, and see what happens.
It's pretty much the same as accessing Math.PI or any other global constant (which also have public and final modifiers).
In your case you have default (package) scope.
It's independed of inheritance only the scope restricts whether it is visible.
I think you might be wrong about static variables not being inherited. I suppose some properties of it are not inherited. For instance a static var normally means that all instances of the class have access to the same place in memory.
When you inherit, the derived class does not refer to the same memory as the base class.
Static member can be static data member and static method which can be accessed without using the object. It is used by nested class