This question already has answers here:
Overriding interface's variable?
(4 answers)
Closed 5 years ago.
Here we go with my question:
I have an interface with a static variable nr
public interface TestInterface {
public static int nr = 1;
}
And a class which implements that interface and has it's own static variable nr too.
public class TestClass implements TestInterface {
public static int nr = 2;
}
And I can actually do this without an error!
public static void main(String args[]) {
TestClass test = new TestClass();
System.out.println(TestClass.nr);
}`
Question: Why would this be allowed?
As far as I understand static fields should be universal through a class instances but what about the superclass - subclass relation?
It's explicitly allowed by the language.
If the class declares a field with a certain name,
then the declaration of that field is said to hide
any and all accessible declarations of fields with
the same name in superclasses, and
superinterfaces of the class.
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3
In your code, both of the static fields are actually defined/meant for separate types i.e., one for TestInterface interface type and other for TestClass class type.
One point you need to understand is that, when it comes to static, there is no overriding, so they will be treated as separate fields.
In superclass - subclass relation the super class's static variables is shadowed by sub class's static variables if they have same name. Because the static variables aren't polymorphic.
Related
This question already has answers here:
Cannot make a static reference to the non-static field memberVariable with private variable
(3 answers)
Closed 3 years ago.
Error: java: non-static method a() cannot be referenced from a static context
I get this error on the following code.
enum ENUM
{
A()
{
{
a();
}
}
,
;
private void a()
{}
}
I expect this to compile, but it doesn't.
Changing the access level modifier private from method a() to any other lets the code compile.
What may prevent this code from compiling?
You get this compile error because enum constants like A here are implicitly static. That's the reason we can use the enum constants like eg: ENUM.A in any other class.
Thus we cannot call a non-static method from a static context. Refer this documentation for more details on enums
The error message is misleading. It's not limited to enums, or to initializer blocks or anything. The problem is simply that an anonymous inner class cannot access private methods from its enclosing class.
private states that sub-classes should not have visibility, and an anonymous inner class is a sub-class so it makes logical sense.
You can observe the same problem with this example:
class Foo {
public static void main(String[] args) {
Foo foo = new Foo(){
void bar() {
a();
}
};
}
private void a(){ /* do nothing */ }
}
This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 7 years ago.
I am using a Inheritance concept here. I have extended class A(Superclass) into class B(Subclass). And I have created an object of a subclass and by using that object I have called add() method. But it is printing a value 5(Super Class).
Why it didn't take subclass's value which is 10 ?
class A{
int a=5;
public void add(){
System.out.println(a);
}
}
class B extends A{
int a=10;
}
public class InheritExample {
public static void main(String args[]){
B b1=new B();
b1.add();
}
}
Help Appreciated.
Thanks.
There's no overriding of instance variables. Overriding only works on instance methods. Therefore, the method add of class A has access only to the a variable declared in A, even if you call that method for an instance of class B.
This question already has answers here:
What is the default access specifier in Java?
(12 answers)
Closed 8 years ago.
Members of a class are private by deafult. The following code doesn't work.
#include<iostream.h>
class Test
{
int x;
};
void main()
{ Test test = new Test();
test.x=10;
}
However the same code works in Java?
class Test {
int x=5;
}
public class MyClass{
public static void main(String args[]) {
Test test = new Test();
System.out.println(test.x);
}
}
According to me it should not work.. since int x is private by deafult, it should not be available to MyClass.
I think the default modifier is package private. Thus you can use test.x in a class which is in the same package as class Test.
No visibility modifier does not indicate that the member is private. If members were private by default, why would the private keyword be allowed on members? That'd be rather redundant.
Instead, no visibility modifier on a member means that the field is package-private -- that is, only visible to other classes in the same package as the member.
Also, struct doesn't exist in Java. You might be getting confused with another language... The only place where members are public by default are interfaces (and maybe enums?), provided the containing interface/enum is also public.
Why are you not able to declare a class as static in Java?
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
Oracle tutorial on nested classes
On the same topic :
Java: Static vs non static inner class
Java inner class and static nested class
Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.
So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.
At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.
Class with private constructor is static.
Declare your class like this:
public class eOAuth {
private eOAuth(){}
public final static int ECodeOauthInvalidGrant = 0x1;
public final static int ECodeOauthUnknown = 0x10;
public static GetSomeStuff(){}
}
and you can used without initialization:
if (value == eOAuth.ECodeOauthInvalidGrant)
eOAuth.GetSomeStuff();
...
You can create a utility class (which cannot have instances created) by declaring an enum type with no instances. i.e. you are specificly declaring that there are no instances.
public enum MyUtilities {;
public static void myMethod();
}
Sure they can, but only inner nested classes. There, it means that instances of the nested class do not require an enclosing instance of the outer class.
But for top-level classes, the language designers couldn't think of anything useful to do with the keyword, so it's not allowed.
public class Outer {
public static class Inner {}
}
... it can be declared static - as long as it is a member class.
From the JLS:
Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (ยง8.1.3).
and here:
The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.
As explained above, a Class cannot be static unless it's a member of another Class.
If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.
Beginner Singleton info here.
Caveat:
If you are thinking of using the
singleton pattern, resist with all
your might. It is one of the easiest
DesignPatterns to understand, probably
the most popular, and definitely the
most abused.
(source: JavaRanch as linked above)
In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:
public enum StaticClass2 {
// Empty enum trick to avoid instance creation
; // this semi-colon is important
public static boolean isEmpty(final String s) {
return s == null || s.isEmpty();
}
}
Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.
So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.
If You are just replacing the object every time you run it whats the point of creating it?
So that is the reason Java got rid of the static for top-Level Class.
There might be more concrete reasons but this made much logical sense to me.
The only classes that can be static are inner classes. The following code works just fine:
public class whatever {
static class innerclass {
}
}
The point of static inner classes is that they don't have a reference to the outer class object.
I think this is possible as easy as drink a glass of coffee!.
Just take a look at this.
We do not use static keyword explicitly while defining class.
public class StaticClass {
static private int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
Is not that a definition of static class?
We just use a function binded to just a class.
Be careful that in this case we can use another class in that nested.
Look at this:
class StaticClass1 {
public static int yum = 4;
static void printHowAreYou() {
System.out.println("How are you?");
}
}
public class StaticClass {
static int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
StaticClass1.printHowAreYou();
System.out.println(StaticClass1.yum);
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
One can look at PlatformUI in Eclipse for a class with static methods and private constructor with itself being final.
public final class <class name>
{
//static constants
//static memebers
}
if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.
This question already has answers here:
Closed 14 years ago.
Duplicate: What does the 'static' keyword do in a class?
I've read this post already.
What does the "static" keyword in a method do?
I remember being told that static != clingy...but that is pretty much all I know about this keyword.
Static class variables can be thought of as a global class. No matter how many instances of the class you have, there is just one instance of each static variable.
Static methods don't use any non-static class variables and they can be called directly from outside of the class without having to instantiate the class itself.
Static variables and methods belong to the class and not instance, although you can refer them from an instance reference. Usually, you use the Class name to access them.
If a method is declared as static, you don't need the object's instance in which it is defined to invoke it. Now, you might want to know when could such a situation arise? Consider the main method of java
public static void main(String[] args)
Why is it declared static? It's because in order to start your program this method should begin execution. And, since the program hasn't initialized there is no way you could create an instance of the class in which it is declared. Therefore, you are required to declare the class as public. And, this static method gets called when the class is loaded in memory through
java YourClassName
Besides this, static methods are used to modify static variables. They cannot manipulate non-static instance variables.
Also, be aware, that static holds a different meaning in another language like C.
A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do. As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method. There's no "this" for the static methods to get access of the non-static fields from.
The Java Math class is a great example because it's loaded with static methods. You never create an instance of the Math class, you just call methods directly from the class.
Math.abs(3.14);
The value of a static variable within a method is stored between calls to that method
public void method() {
static int callCount = 0;
callCount++;
System.out.println("Calls: " + callCount);
}
method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"
Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.
class MyClass {
public static void staticMethod() { ... }
public void nonStaticMethod();
}
Myclass.staticMethod();
MyClass instance = new MyClass();
instance.nonStaticMethod();
a static method is one that's established for the class. It doesn't need (and doesn't have) a this pointer, and can't access instance data. So you can write something ike
public class Hello {
void instanceHello() {
System,out.println("Hello from the instance.");
}
public static void main(int argc, String[] argv){
// The main method is defined even though there are no instances
System.out.println("Hello from main.");
instanceHello(); // but this is a syntax error;
Hello h = new Hello();
h.instanceHello(); // this isn't though
}
}