Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
class test
{
public static myclass x;
test() {
try {
x=new myclass();
//x is not null here
} catch(Exception e) {/*stuff*/}
//not null here
}
//x is null here in any other member method
}
Please explain a reason for this behavior?
Isn't a constructor required to retain a value rather than losing it once a constructor block ends?
You seem to be confusing static values with instance values.
x is static, but it's not initialized in a static initialization block. It's only initialized when you create an instance of test (via the constructor for that instance). Also note that it's going to be re-initialized any time you create a new instance of test, which is probably going to cause some very strange bugs for you.
In order for x to be initialized as a static value for the class, add it to a static initialization block:
class test
{
public static myclass x;
static
{
x=new myclass();
}
}
This way x should only be initialized once, statically, when the runtime loads the class. This would allow it to be accessed without first having to create an instance of test, as well as remove the bug of re-initializing it on any new instance of test.
Conversely, if this should instead be an instance value instead of a static value, you can simply change its declaration:
public myclass x;
as such code is correct. but since the variable x is static, you might be accessing it before calling the constructor. in that case it will be null. As soon as, the constructor get to run for the first time, the value of x will be set to a new object.
if its you requirement to keep x static. initialize it in static initializer block. like:
class test
{
public static myclass x;
static {
x = new myclass();
}
}
or simply as:
class test
{
public static myclass x = new myclass();
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I have a simple nested class A. (In C I would use a struct.) I want to provide a default object A.DEFAULT of class A without having to call the constructor each time. So my idea was this:
class MyApplication {
class A {
int x;
double y;
public static final A DEFAULT = new A(0, 0.0);
public A(int x, double y) {
this.x = x;
this.y = y;
}
}
…
Obviously, this does not work, because the constructor cannot be called before the class has been loaded.
How to handle this?
How does e. g. java.awt.Color.RED handle this?
This has nothing to do with constructor calls, you've just made a couple of simple mistakes.
You haven't specified a type for DEFAULT:
public static final A DEFAULT
You cannot instantiate an A without an instance of MyApplication, as A is an inner class:
new MyApplication().new A(0, 0.0);
However you probably didn't intend to make A an inner class, so I would mark it as static. Without any extra context, it seems as if A has no relation to MyApplication so shouldn't depend on it.
Note: In Java 15 and below, static declarations weren't even allowed in inner classes (as pointed out by #Johannes Kuhn).
Apart from the obvious problem that you missed a type (A) on the definition of DEFAULT...
The problem isn't that "the class has [not] been loaded". The problem is that, in Java, every instance of an inner class implicitly has a reference to the instance of the outer class that created it. Since there is no instance of the outer class when initializing the static field, you get an error:
MyApplication.java:5: error: non-static variable this cannot be referenced from a static context
public static final A DEFAULT = new A(0, 0.0);
^
And in all but the most recent Java versions, even declaring a static field inside a non-static inner class is illegal, no matter what value you give it:
MyApplication.java:5: error: Illegal static declaration in inner class MyApplication.A
public static final A DEFAULT = new A(0, 0.0);
^
modifier 'static' is only allowed in constant variable declarations
The solution is to make the inner class not have a reference to the outer class, which you do by declaring A as static:
class MyApplication {
static class A {
^^^^^^
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Can we call static method via a temp variable?
There is a class AA
class AA {
static void test() {
}
}
class Main {
public static void main(String[] args) {
var aa = AA;
aa.test(); // Can we call static method via a temp vairble ?
}
}
Why I have the question? Because I must modify all the instance call style to class static style in my refactor work. The method was an instance method before and use a local variable to call it and now it became a static method or class. So I consider if there is way that just modify the variable. Maybe it's naive.
Directly, maybe like this, but not right.
Class<AA> aa = AA;
aa.test();
I know it's not good way to call static method by a instance as well.
And we know there is a way in Java 8 to refer a function. So is there another more meta capability to refer a literal class?
Can we call static method via a temp variable ?
Yes, you can. (Modulo the compilation errors!)
But you are probably not doing what you think you are doing with this. And it is a bad idea.
In fact, aa.test() actually means exactly the same thing as writing Variable.test(). That is, the value of aa and its actual type are completely ignored in determining which method is called, and in calling the method1.
The class whose test() method is invoked is resolved to Variable at compile time. Java does not support overriding or dynamic dispatching of static methods.
1 - The JLS states that the expression that computes the reference is evaluated, but the resulting reference is then discarded.
Invoking a static method via an instance variable is bad style, and should be avoided.
Consider this:
class AA {
static void test() {
System.out.println("AA");
}
}
class BB extends AA {
static void test() {
System.out.println("BB");
}
}
class Main {
public static void main(String[] args) {
AA aa = new BB();
aa.test();
}
}
Q: What is the output?
A: The output is "AA".
Actually, that is not how to call a static method from a class.
If we have class AA :
class AA {
public AA() {}
public static void test() {
System.out.println("Test");
}
}
We can call the test method like this:
AA.test();
It is not recommended to call static method from it's instance like this:
AA aa = new AA();
aa.test();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In java, after using a particular wrapper class in the generics of that class, we can't use that particular wrapper class in any static method or instance method or instance variable of that class. And another problem is the constructor which can only accept Integer object is accepting Strings(or any other wrapper class object) too. Look at the code below,what is the reason behind these compilation errors?
public class Exp<Integer> {
Integer val1;
Integer val2=new Integer(2);//compilation error, cannot instantiate the type Integer
public Exp(Integer arg1){
System.out.println(arg1);
val1=arg1;
}
public void lol(){
// Integer intValue2=new Integer(2);//compilation error, cannot make static reference to the non static type Integer
}
public static void main(String[] args){
Exp obj1=new Exp(10);
// Exp obj2=new Exp("Hello world");
// Exp<String> obj3=new Exp<String>("sss");// The constructor takes Integer arg, then why is string arg working perfectly with it?
String str="10";
Character c=new Character('c');//works perfectly
Float f1=3.0f;
Integer intValue1=new Integer(2); //**compilation error, cannot make static reference to the non static type Integer**
Exp<Integer> obj4=new Exp<>(10); //**compilation error, cannot make static reference to the non static type Integer**
}
}
Here you are not using "wrapper class in the generics", you just named your generic type variable as an existing class in java.lang package which hides the original class. However you may still access the original class using fully-qualified name:
java.lang.Integer val2 = new java.lang.Integer(2);
The same for other places where you have compilation error. In general it's better to avoid such names which clash with java.lang classes. Probably you actually wanted to write something different, like
public class Exp extends SomeOtherGenericClass<Integer> { ... }
The type in angle brackets is a dummy which is substituted for the actual type later. It is common to use <T>. You have used a real type, <Integer> which hides the system class Integer, so Integer in your program is no longer referring to java.lang.Integer, leading to the error messages.
Your code should look like this:
public class Exp<T> {
T val1;
...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have this situation:
public class Number {
int num;
private TakeNumber take = null;
public Number() {
num = 5;
}
public void print() {
take.doSomething();
}
public int getNumber() {
return num;
}
public static void main(String[] args) {
new Number();
}
}
public class TakeNumber {
private Number number = new Number();
public void doSomething() {
System.out.println(number.getNumber());
}
}
Now, can someone explain me these situations:
I want to know what the compiler interprets here : private Number number = new Number();
Initialize the object in question and passing the required methods
Is correct initialize one object to null and then call a function on that object, as shown
in brief
I would like to know if you can call a method of a class of another class:
without the required function to be static
IMPORTANT do not inherit the classes because I want to use methods of these classes, for example:
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
I would like to know if you can call a method of a class of another class:
without the required function to be static
If the methods are not static, then you will need an instance of that object to call it.
Object o = new Object();
o.doSomething();
Is how you access an instance method.
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
This is fine. This is called composition. Composition is a has a relationship between classes. A class Man has a class Car, but Is a class Person. And it is perfectly valid to write code as you have shown. This is how you use composition to expose only the interface of a composite object that you want. For example..
public class MyClass extends MyOtherClass
Now you've just exposed the whole interface of MyOtherClass. This might not be desired.
public class MyClass {
MyOtherClass otherClass;
public void doSomething() {
otherClass.doSomething();
}
}
Now, you've only exposed the doSomething() method. This is useful when, as you said, your objects are conceptually different, but require some shared functionality. It is a perfectly valid code practise.
NOTE: Given the confusing nature of your question, I imagine I've missed some stuff out so please comment with desired edits.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass.
following is the code that raised the doubt
class Test {
public int a = 10;
}
class TestChild1 extends Test {
public int a = 20;
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.a); // results in 10
}
}
Please give me the reasons for this behavior. Thanks in advance....
Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.
When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.
When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.
OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.
The class TestChild1 has two variables with the same name. If you access them through Test you get the first one, from TestChild1 you get the second one.
To get your expected result, you should not declare a in the derived class. Instead you should initialize it in the costructor of the derived class.
You declared your object as Test, not the subclass. At compile time that means you refer to the base class which has 10.
Because behavior is associated with methods and not with fields.
So, fields have static binding (in this case this, since test is of type Test, value of a is assigned with value 10). Whereas methods have dynamic binding.
Since, the variable a doesn't define the behavior of Test class, it is assigned the value as per its type and not as per its instance.
JB Nizet have already said everything, but I will add this code for more understanding:
class Test {
private int a = 10;
public int getA() {
return a;
}
}
class TestChild1 extends Test {
private int a = 20;
public int getA() {
return a;
}
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.getA()); // results in 20
}
}
So if you would encapsulate your fields, you would have expected behaviour.