I have an abstract superclass called operation.java and several subclasses extending this class and representing operations. Each such subclass should contain an array of normalizing contants which should be static because it holds globally. I have the following example:
abstract class Operation {
private static double[] normalizingConstants;
protected Operation() {
normalizingConstants = new double[10];
}
}
class AddOp extends Operation {
protected AddOp() {
super();
}
}
class MinusOp extends Operation {
protected AddOp() {
super();
}
}
Does each subclass hold its own static normalizingConstants? If I call AddOp.normalizingConstants[0] and MinusOp.normalizingConstant[0] I want different results. How can this be achieved?
Does each subclass hold its own static normalizingConstants?
No, there is only one normalizingConstants (Operation.normalizingConstants). static fields are tied to the class where they are declared.
If I call AddOp.normalizingConstants[0] and MinusOp.normalizingConstant[0] I want different results. How can this be achieved?
If you need different normalizingConstants arrays, you need to declare another static variable in your sub classes, like
class MinusOp extends Operation {
private static double[] normalizingConstants;
...
Note that your normalizingConstants fields are only accessible from within the delaring classes since they are declared private.
Also, you should not initialize your static array in the constructor - use a static initializer instead. Otherwise, the array is re-initialized each time you create a new instance of your class (or any sub class).
Related
Hi I have two interface Ainterface and Binterface having same static final variable as 'i' which is declared as 10 and 20 respectively, I am implementing these two interfaces two my class InterfaceCheck where I am declaring same interface variable as static and final and initialized to 30. When I try to print the value of i in my class I am getting 30 as output. can some one explain me why I am able to reinitialize i to some other value even though its a final variable.
CODE
public interface Ainterface {
public final static int i=10;
}
public interface Binterface {
public static final int i=20;
}
public class InterfaceCheck implements Ainterface,Binterface {
public static final int i=30;
public static void main(String[] args) {
System.out.println(i);
}
}
>> output : 30
Class fields are always resolved on the static type of the reference.
In
public static void main(String[] args) {
System.out.println(i);
}
it implicitly does
System.out.println(InterfaceCheck.i);
so that is what you see.
Also, static fields are not inherited.
Static variables belong to the class itself (not to the instance) and these variables are not inherited by child class or implementing class.
Therefore:
public class InterfaceCheck implements Ainterface,Binterface {
public static final int i=30;
}
is not overriding i from those 2 interfaces. It is actually declaring a new independent static final variable.
Java has single inheritance because multiple inheritance has the problem of which members to pick when inherited classes collide on member names. But Java provides interfaces because that provides much of the power of multiple inheritance (additional behaviors) without the risk of name collision (but at the cost of choosing which methods so provide when method signature collision occurs).
Allowing class variables in interfaces is a relaxation of this rule, but was probably allowed because of where the member variable is located (one per class). As anubhava and Sotirios said they are not inherited, but declaring a new member, obscuring the inherited variable.
Your question concerns lexical scope. Since you have declared three 'public' variables which are class members, then you need to resolve scope. Since you have two inherited interfaces, do you really mean to define/set your own class variable, or to modify one or both of the inherited interface class variables?
I recommend you play around with the code to understand it fully whats going on, Very old thread here but all the same just wanted to add the following:
Comment out the static class "i" and when you run the code you will see java telling you "reference to i is ambiguous" ie, it does not know which one you want to call as it exists in both interfaces. Now un-comment the class static "i" and add two more printouts with the reference to both interfaces. As they are static this is allowed.
public static final int i=30;
public static void main(String[] args) {
System.out.println(i);
System.out.println(Ainterface.i);
System.out.println(Binterface.i);
}
30
10
20
Again if you remove the InterfaceCheck class static "i" constant and remove one of the interfaces it implements, say Binterface. You can reference the constant from Ainterface without its explicit reference as its the only static "i" created.
public class InterfaceCheck implements Ainterface {
public static void main(String[] args) {
System.out.println(i); //This will out Ainterface.i value of 10
//System.out.println(Ainterface.i);
//System.out.println(Binterface.i);
}
I am doing some research on JAVA initialization process.
Here is a good material for reference:
When a class is loaded and initialized in JVM
On this page there is rule says:
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type of Sub Class, Sub Interface or by implementation class of interface.
I really don't understand the idea. If the static field is referenced by Sub class, then this field of course need to create a sub class object or assigned by a Sub class object.
So, it definitely triggers Sub class initialization.
What's wrong with my interpretation?
EDIT:
It DOES trigger Super Class static initialization.
If the static field is final, and the static final field is initialized when declaring. Then it will neither load the class nor initialize the class, for this static final field is a compile time constant value. Attention: if the static final field is initialized in static block, then this statement does NOT hold anymore.
I think the point is that in a situation like this:
public class Superclass {
public static long INIT_TIME = System.currentTimeMillis();
static {
System.out.println("Initializing Superclass");
}
}
public class Subclass extends Superclass {
static {
System.out.println("Initializing Subclass");
}
}
This code:
long time = Subclass.INIT_TIME;
is actually compiled to:
long time = Superclass.INIT_TIME;
and only "Initializing Superclass" will be printed, even though the source code referred to Subclass.
An example:
class A {
public static int nA = 0;
}
class B extends A {
public static int nB = 1;
}
class C extends B {
public static int nC = 2;
}
Client:
int test = B.nA;
The JVM will initialize only Class A. Not B nor C.
As shown above, when I run the Superclass/Subclass example, on calling Subclass.INIT_TIME,
both the Superclass and Subclass static initializers are getting invoked.
But here it is said that only "Initializing Superclass" will be printed.
Can someone clarify?
Apologies if this has been posted before, I keep only getting results for overriding the opposite way.
I want to be able to do 2 things:
Reference the parent variable from the child class, in assigning the value for the child variable.
Have the method in the adult class that references this variable use the child classes value. That way, I can have a lot of child classes, but not have the same repeating code for the method.
Here's a super simple pseudo-example of what I mean:
child class:
public class ChildClass extends AdultClass {
static int a=super.a+1;
}
adult class:
public class AdultClass {
static int a=5;
static public int getA() {
return a;
}
}
class that uses ChildClass object:
public class ClientClass {
public static void main(String[] args) {
ChildClass.a <-I want this to =6
ChildClass.getA() <-I want this to return 6
}
}
If you want to leverage Java's polymorphism, you'll have to involve class instances. Static members cannot display polymorphic behavior, which you apparently require from AdultClass.getA().
then simply make the member a protected one, and use it as the child's own member.
this link may be useful too.
why instance variable of super class is not overridden in sub class method
I have a Java problem with nested classes.
My first class structure looked like this:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private interface NestedClass {
public void method();
}
private class NestedClass1 {
public void method() {
}
}
private class NestedClass2 {
public void method(){
}
}
}
But now I want these method() methods to be static because they should be principally.
I cannot make them static without having them in a static class, but that's no problem, I made the classes static, they should be anyway.
It looks like this right now:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private static interface NestedClass {
public void method();
}
private static class NestedClass1 {
public static void method() {
}
}
private static class NestedClass2 {
public static void method(){
}
}
}
But then the trouble begins. A static method does not inherit correctly from a non-static interface method, as I get this message This static method cannot hide the instance method from TopClass.NestedClass in Eclipse.
When I make the interface method static, it gives me this error: Illegal modifier for the interface method method; only public & abstract are permitted
So I thought of an abstract class, and tried this:
public class TopClass {
public void mainMethod() {
// uses the different "method" methods from
// NestedClass-implementing nested classes
}
private static abstract class NestedClass {
public static abstract void method();
}
private static class NestedClass1 {
public static void method() {
}
}
private static class NestedClass2 {
public static void method(){
}
}
}
But again, seemingly abstract methods cannot be declared static: The abstract method method in type NestedClass can only set a visibility modifier, one of public or protected.
Leaving the static away (in the abstract class method), errors this on the method methods in the NestedClass1 & 2: This static method cannot hide the instance method from TopClass.NestedClass.
Isn't there any way to declare some kind of superstructure for covering static methods?
EDIT:
The problem I actually try to solve it the lack of possibility of Java for storing references to methods. So instead I have those classes everyone with just one method, but to store them in a List f.e. they must be able to be "caught" by a superstructure.
I got the hint to try anonymous classes or enums, gonna try that now.
Interfaces and statics don't go together. At all. There is no Java support for creating / imposing patterns on static methods.
A static method declaration must always be followed by a definition. It cannot be implemented by subclasses.
I think you're just not approaching your problem right. Try a different approach!
Make NestedClass an interface NestedInterface and store your different implementations as anonymous classes implementing this interface:
public static final NestedInterface firstNested = new NestedInterface() {
#Override
public void method() {
// ...
}
};
Make NestedClass an enumeration NestedEnum and store your different implementations as enumeration values implementing an abstract method from the enumeration. This only works if you have a fixed number of implementations you which to choose from and you do not want to accept NestedClass implementations from outside sources.
public enum NestedEnum {
FIRST {
#Override
public void method() {
// ...
}
};
public abstract void method();
}
EDIT: In reply to your comment:
The classes itself are static as well..
static in the context of a nested class means that this class can be instantiated without an instance of the containing class.
A regular nested class such as in your first example can be instantiated through TopClass.this.new NestedClass1(). Normally you'd simply write new NestedClass1() from within the constructor or an instance method of TopClass, but in this verbose form you can clearly see the dependence on TopClass.this. This can also be seen from any method of NestedClass1, as you have access to the containing class with TopClass.this.
A static nested class such as in your second example can be instantiated through new TopClass.NestedClass1(). Once again, you could just write new NestedClass1() but the verbose form clearly shows that the construction only depends on TopClass and is not associated with an instance of TopClass. You could even create an instance from an outside class using the same snippet new TopClass.NestedClass1() without ever creating a TopClass instance.
I suggest you take a look at this question on inner classes and static nested classes.
The fact the your interface/abstract class is nested is irrelevant to the problem.
You just can't. There is no way in Java to enforce some class to implement static methods. Just cry and surrender and use instance methods.
static abstract is a contradiction. Static methods are not like other languages' class methods. When you make a static method it goes on a single class, it doesn't get inherited by or have its implementation deferred to subclasses.
You don't explain why you want these methods to be static. If you want these methods to be defined by subclasses then they shouldn't be.
I have an abstract class and 2 subclasses. There are 4 constants that relate to all the classes. I was going to place the finals in the abstract class but I understand a final variable is not inherited?
Would I have to define the constant in every class (seems inefficient)? Or just make the constant an instant variable (doesn't sound like a good idea)?
What are ways I can go about this?
The following would be available to all of your sub-classes if defined in the abstract class.
public static final Integer MYCONSTANT = 42;
or
static final Integer MYCONSTANT = 42;
or
protected static final Integer MYCONSTANT = 42;
The second one (package-private) is only available to classes within the same package. The third (protected) would be available to all sub-classes irrespective of their package.
Constants are inherited by childrens. You just have to make sure to have them protected or public so the children can access them.
abstract class A {
protected final static String FOO = "bar";
}
class B extends A {
somemethod() {
System.out.println("foo: " + FOO);
}
}
can be accessed from the class and all its children.
Yes they are. But as they are constant it should be final and static , static modifier make it there will be only one 'copy' and if this will be used only used in subclass only then u can use protected or if from other Classes too the must make it public.