As I read from various Java book and tutorials, variables declared in a interface are constants and can't be overridden.
I made a simple code to test it
interface A_INTERFACE
{
int var=100;
}
class A_CLASS implements A_INTERFACE
{
int var=99;
//test
void printx()
{
System.out.println("var = " + var);
}
}
class hello
{
public static void main(String[] args)
{
new A_CLASS().printx();
}
}
and it prints out
var = 99
Is var get overridden? I am totally confused. Thank you for any suggestions!
Thank you very much everyone! I am pretty new to this interface thing. "Shadow" is the key word to understand this. I look up the related materials and understand it now.
It is not overridden, but shadowed, with additional confusion because the constant in the interface is also static.
Try this:
A_INTERFACE o = new A_CLASS();
System.out.println(o.var);
You should get a compile-time warning about accessing a static field in a non-static way.
And now this
A_CLASS o = new A_CLASS();
System.out.println(o.var);
System.out.println(A_INTERFACE.var); // bad name, btw since it is const
You did not override the variable, you shadowed it with a brand-new instance variable declared in a more specific scope. This is the variable printed in your printx method.
Default signature for any variable in an interface is
public static final ...
So you cannot override it anyhow.
The variable you declared in that interface is not visible to the class that implemented it.
If you declare a variable in an static and final, i.e. a constant, THEN it is visible to implementors.
Related
I have a question when I saw "Instance variables can be declared in class level before or after use." in the site java_variable_types
I don't understand what is the class level and the meanning of this sequense.
I think they mean that this is legal:
public class Test {
private int someValue;
public int myMethod() {
return someValue + anotherValue;
}
private int anotherValue;
}
(And it is!)
However, I think it is a mistake for the site to describe this as "[i]nstance variables can be declared in class level before or after use".
The phrase "declared in class level" is bad English grammar.
The phrase "in class level" is ambiguous. It could mean declared in the body of a class. However, it could also mean declared as "class-level" (i.e. static) variables. (That is contradictory, and incorrect, but ...)
The phrase "before or after use" is ambiguous. It could mean before or after in the source code file. It could also mean in before or after in the temporal sense. (That would be incorrect. At runtime, all of an object's instance variables are declared and initialized before the code in a method or constructor body is executed.)
While what they are trying to say (I think) in that sentence is correct, they have expressed themselves poorly, and it is clearly causing confusion for some readers.
Instance variable val is declared in line #2( please note the marking) but referenced even before in line #1. You can remove comment from line #3 and comment line #2. Then also it will work.
It means variable val using in line #1 even before declare in case if line#2 consider using after if you consider line#3.
public class prog{
//private int val; //line# 3
public int getVal()
{
return val;//line# 1
}
private int val; //line# 2
prog()
{
val=0;
}
public static void main( String [] args)
{
prog obj= new prog();
System.out.println("val:"+obj.getVal());
}
}
While your reference does a good job of explaining it, I'll add some details for completeness.
An instance variable...
is declared at the class level
can have any visibility that is necessary (public, protected, private, or no modifier to signify package-private)
will receive an initial value after instantiation (that is, you don't have to instantiate the field with a value...but if you don't instantiate a reference value, you may run into a NullPointerException)
The phrase "before or after use" doesn't make much sense, but let's illustrate a scenario:
public class Foo {
private String word;
public void printTheWord() {
System.out.println(word);
}
}
word hasn't been instantiated, but we can use it since it's received an initial value of null. This means that we won't get the value we want, but it will compile.
Contrast this with a local variable. The below code won't compile because word hasn't been instantiated.
public class Foo {
public void printTheWord() {
String word;
System.out.println(word);
}
}
The phrase "before or after use." would mean that the instance variable, which is applicable to the class as a whole ,unlike local variable which is restricted only inside of that method.
It can be declared or initialized at the start of the class,which is generally the most likely way.
Other , inside of the class, it can be declared , after the call of the method using it.
Please find the below code snippet to understand the phrase:
public class InstanceVariable {
//declared before
int foo=4;
public void testInstanceVariableUse(){
System.out.println("The total value of the instance variable is "+ (foo+boo));
}
//declared after
int boo=5;
}
class TestInstanceVariable{
public static void main(String[] args){
InstanceVariable instanceVar = new InstanceVariable();
instanceVar.testInstanceVariableUse();
}
}
Output:
The total value of the instance variable is 9
in java we are able to "invoke a static method with class name" and also "invoke a static method with an object"
what is the difference between "invoking a static method with class name" and "invoking a static method with an object" in java?
There is no difference but the recommendation is to call the static methods in a staic way i.e. using the ClassName. Generally static analayzers will report an error if you don't do so.
An important thing to understand here is that static method are stateless and hence calling them with an instance is confusing for someone reading your code. Because no matter what instance you use to call the static method, result will remain the same. This is because a static method belongs to a class but not to an object.
Internally, new ClassName().staticMethod(); is considered as ClassName.staticMethod(). So there is no difference. It just causes confusion.
Consider an example
public class StaticDemo {
static int staticVar = 10;
public static void main(String [] args){
System.out.println(new StaticDemo().staticVar);
System.out.println(StaticDemo.staticVar);
}
}
This outputs
10
10
`
even if you write new StaticDemo().staticVar, it will be considered as StaticDemo.staticVar. So there is no difference at all and always use the Class notation to avoid confusion.
There is no difference at all. But since static methods are at the class level, you can access them using the class name. Though invoking them using class object is possible, it creates a confusion. Why would you like to invoke them for every object if its value is going to be the same?
No, there is none. Apart from possible confusion... A reader of such code cannot reliably tell static from non static members/methods apart if you use an instance to access them:
public class X
{
public static final String foo = "foo";
public static String bar() { return "bar"; }
public static void main(final String... args)
{
final X x = new X();
System.out.println(X.foo); // "foo"
System.out.println(x.foo); // "foo" too -- same reference
System.out.println(X.bar()); // "bar"
System.out.println(x.bar()); // "bar" too -- same reference
}
}
As this is confusing, it is generally preferred to use the class to refer to such members/methods.
Static methods do NOT operate on a class. They are just bound to class instead of to member of that class. This means that they don't have access to any non static members of the class. Other than that, they are not very different than the non-static methods.
In SCJP guide book. having a example as following:
class Frog {
static int frogCount = 0; // Declare and initialize
// static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
}
class TestFrog {
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.print("frogCount:"+Frog.frogCount); //Access
// static variable
}
}
But just to make it really confusing, the Java language also allows
you to use an object reference variable to access a static member
Frog f = new Frog();
int frogs = f.frogCount; // Access static variable
// FrogCount using f
In the preceding code, we instantiate a Frog, assign the new Frog
object to the reference variable f, and then use the f reference to
invoke a staticmethod! But even though we are using a specific Frog
instance to access the staticmethod, the rules haven't changed. This
is merely a syntax trick to let you use an object reference variable
(but not the object it refers to) to get to a staticmethod or
variable, but the staticmember is still unaware of the particular
instance used to invoke the staticmember. In the Frog example, the
compiler knows that the reference variable f is of type Frog, and so
the Frog class staticmethod is run with no awareness or concern for
the Frog instance at the other end of the f reference. In other
words, the compiler cares only that reference variable f is declared
as type Frog.
I hope this will help you
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.
Clarification: this question is not about access modifier
Confirmed that B.m() and b.m() statements both works in the following code:
class A {
static void m() { //some code }
}
class B extends A {
}
class Example {
public static void main (String [] args) {
B.m(); // running A's m() static method
}
public void try() {
B b = new B();
b.m(); // running A's m() static method
}
}
My question is can we said "static method is inherited"?
if "inherited" is the correct term, if we add a method to B class we same signature of the static class:
class A {
static void m() { //some code }
}
class B extends A {
static void m() { //some code }
}
class Example {
public static void main (String [] args) {
B.m(); // running B's m() static method
}
public void try() {
B b = new B();
b.m(); // running B's m() static method
A a = new B();
a.m(); // running A's m() static method, no polymorphism
}
}
In this case, notice that we have no polymorphism, is it the correct term to said that "static method is inherited but not overridden, subclass static method hide superclass static method"?
Last doubt, for these 2 terms, "inherited" and "overriden", which one is directly tied to the term "polymorphism" ?
Yes, I think "inherit" is the correct term here, even if it's not as descriptive as it might be. From section 8.4.8 of the Java Language Specification:
A class C inherits from its direct superclass and direct superinterfaces all non-private methods (whether abstract or not) of the superclass and superinterfaces that are public, protected or declared with default access in the same package as C and are neither overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.
That doesn't specify instance methods, but there are specific restrictions on what is allowed to hide or override what, which wouldn't make sense if static methods were not inherited.
Really though, I would simply view static methods as "accessible without qualification" rather than anything else, given that they don't take part in polymorphism etc. I think it's worth being very clear about that - for example, one static method can hide an inherited one, but it can't override it.
In other words, while I think "inherit" is technically correct, I would try to avoid using it without any further explanation.
For your second question, I'd say that based on the above, overriding is tied to polymorphism, but inheriting isn't necessarily.
(I would also strongly advise you to avoid calling static methods "via" variables, and also to use the name of the class which declares the static method wherever you specify the name at all. I know that's not part of the question, but I thought I'd just add it anyway...)
I think trying to apply words like 'inherited' and 'overridden' to this sort of thing is not productive. It's misleading because it gives the impression there is something comparable of what goes on with virtual instance methods, and you point out there isn't.
(But as Jon Skeet points out, the Java language spec doesn't agree with me, it groups these together in the same section.)
Guys I would like to share my knowledge in java with all java lovers out there!
First of all let me tell you that static members are those members which can be accessed directly without creating an object of that particular class, when static members of a class is used in some other class then it should be used by specifying the class name .(dot) static member's name(e.g. A.i in the following example), and also if any subclass class is getting inherited from a super class which has static members and if both subclass and super class are in the same package then that static members can be accessed from the base class without even using the class name of the super class. Please go through the
Example:
package myProg;
class A
{
static int i = 10;
A()
{
System.out.println("Inside A()");
}
}
class B extends A
{
public static void main(String[] args)
{
System.out.println("i = " + i); //accessing 'i' form superclass without specifying class name
System.out.println("A.i = " + A.i); //again accessing 'i' with the class name .(dot) static member 'i'
/*
we can also use the super class' object in order to access the static member compiler
will not show any error but it is not the exact way of using static members. static members are created
so that it could be used without creating the class object. see below the usage of object to use the
static member i.
*/
A obj = new A(); //creating class A object and A() also gets called
obj.i = 20;
System.out.println("obj.i = " + obj.i);
}
}
/*
This program was to show the usage of static member. Now, lets discuss on the topic of static member inheritance.
SO GUYS I WOULD LIKE TO TELL YOU THAT STATIC MEMBERS ARE NOT INHERITED. This undermentioned program is
to show the inheritance of static members.
*/
class A
{
static int i = 10; //initially the value of i is 10
static int j = 20; //lets use one more static member int j, just to see the value of it through class A, and B
static
{
/*
This is static initialization block(SIB) of class A,
SIB gets executed first in the order of top to bottom only one time
when the class is loaded.
*/
System.out.println("A-SIB");
}
}
class B extends A
{
static
{
i = 12;//trying to modify the i's value to 12
System.out.println("B-SIB");
}
}
class D extends A
{
static int k = 15;
static
{
System.out.println("D-SIB");
}
}
class C
{
public static void main(String [] arhs)
{
System.out.println("D.k: " + D.k);
/*here we are trying to access the static member k from class D,
it will try to search this class and then that class
will be loaded first i.e. SIB of class D will be loaded and SOP
statement of class D will be printed first. When the class loading
is done then the compiler will search for the static int k in class
D and if found SOP statement will be executed with the value of k.
*/
/*
ONE GROUND RULE: as soon as the compiler see this statement the compiler will load
class D into the memory, loading of class into memory is nothing but
storing all the static members (i.e. static constant & SIBs) into the
memory.
*/
System.out.println("B.i: " + B.i);
/*Now, this is what we are talking about... we think that static int i's
value is there in class B and when we write B.i it compiles and executes
successfully BUT... there compiler is playing a major role at this statement...
Try to understand now... we know that class B is the subclass of class A
BUT when the compiler sees this statement it will first try to search
the static int i inside class B and it is not found there, then since it is
the subclass of A, the compiler will search in class A and it is found
there. NOW, WHEN STATIC INT I IS FOUND IN CLASS A THE COMPILER WILL CHANGE
THIS STATEMENT B.i TO A.i and the class B WILL NOT AT ALL BE LOADED INTO
THE MEMORY BECAUSE STATIC I IS ONLY PRESENT IN CLASS A. But in the previous
statement static int k is present inside class D so when we try to access k's value
the class D will be loaded into memory i.e. SIB will be executed and then
the SOP statement of the value of k. USING B.i IS NOT WRONG BUT COMPILER
ASSUMES THAT THE PROGRAMMER HAS MADE A MISTAKE AND IT REPLACES THE CLASS NAME
B.i TO A.i. Thus this show that static members are not inherited to the subclass.And
therefore the vaue of i will NOT BE CHANGE TO 12 AS YOU CAN SEE IN THE SIB OF
CLASS B, it will be 10 only..
*/
System.out.println("A.j: " + A.j);//this statement will be executed as it is, compiler will not make
System.out.println("A.i: " + A.i);//any modifications to these statements.
System.out.println("B.j: " + B.j);//again compiler will modify this statement from B.j to A.j
}
}
Guys if you still have any confusion mail me at this email-id:
pradeep_y2k#yahoo.co.in
Regards
Pradeep Kumar Tiwari
Ok static methods cannot be overridden but can be redefined in other words its called hiding
check this http://www.coderanch.com/how-to/java/OverridingVsHiding they explain pretty well
If I create an instance of a class in Java, why is it preferable to call a static method of that same class statically, rather than using this.method()?
I get a warning from Eclipse when I try to call static method staticMethod() from within the custom class's constructor via this.staticMethod().
public MyClass() { this.staticMethod(); }
vs
public MyClass() { MyClass.staticMethod(); }
Can anyone explain why this is a bad thing to do? It seems to me like the compiler should already have allocated an instance of the object, so statically allocating memory would be unneeded overhead.
EDIT:
The gist of what I'm hearing is that this is bad practice mainly because of readability, and understandably so. What I was really trying to ask (albeit not very clearly) was what differences there are at 'compilation', if any, between calling MyClass.staticMethod() or this.staticMethod().
Static methods are not tied to an instance of the class, so it makes less sense to call it from a this than to call it from Class.staticMethod(), much more readable too.
MyClass.staticMethod() makes it clear that you are calling a static (non-overrideable) method.
this.staticMethod() misleads the reader into thinking that it is an instance method.
staticMethod() is also on the misleading side (though I normally do it that way).
If you think of people reading your code as unfamiliar with it you tend to try to make the code clearer, and this is a case where the code is clearer by having ClassName.method instead of instance.method.
In addition to the other answers which have mentioned making it clear you're using a static method, also note that static methods are not polymorphic, so being explicit with the class name can remove any confusion as to which method is going to be called.
In the code below, it's not entirely obvious that b.test() is going to return "A" if you're expecting the polymorphism of a non-static method:
public class TestStaticOverride
{
public static void main( String[] args )
{
A b = new B();
System.out.println( "Calling b.test(): " + b.test() );
}
private static class A
{
public static String test() { return "A"; }
}
private static class B extends A
{
public static String test() { return "B"; }
}
}
If you change the code to B b = new B(); it will print out "B".
(Whether it's ever a good idea to "override" static methods is probably a discussion for another day...)
Static methods are really not part of your instance - and it will not be able to access any of your instance variables anyway, so I would dare thinking it doesn't make a lot of sense calling it from the constructor.
If your need to initialize static objects use
private static List l = new ArrayList(); static { l.add("something"); }
If you still need to call it its perfectly legal to call local static methods without prefixing your local class name, like this (no eclipse warning)
public MyClass() { staticMethod(); }
Because this. normally reference to instance methods, therefore, it's a bad idea to do that.