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;
...
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 1 year ago.
Improve this question
I'm wondering how I would get a class from a java.lang.Object object to a specific class, such as a Cat class I may write; not directly casting to Cat, but to automatically get the main class of the object and cast to the main class, since I may take in Object arguments to take in many kinds of classes. Would getting an object through Class<T>, getting T (the type of the main class) be possible?
Here's what I mean:
class Cat {
public String meowMessage = "meow";
public void meow() {
System.out.println(meowMessage);
}
}
public class Main {
public static void main(String[] args) {
Object obj = new Cat();
// Cat c = obj.getClass()...;
// ^ how to get the Class object and automatically cast to the main class (Cat)?
}
}
What you want would involve determining a generic parameter at runtime. This is not possible due to type erasure.
If I understand correctly, you need instanceof so you can write:
if (obj instanceof Cat) {
Cat cat = (Cat) obj;
cat.meow();
} else {
//do something else
}
It's not possible to cast to a type which is not known compile time and I don't think it would make any sense because casting is needed to access the members of the class instance statically from the code. But how to know what is accessible if the class is unknown?
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 5 years ago.
Improve this question
When I run this code the output is (MyInt#15db9742)-Object Address-:
public static void main(String[] args) {
MyInt myInt = new MyInt(2);
System.out.println(myInt);
}
class MyInt {
public int val;
public MyInt(int val){
this.val = val;
}
}
What I want to do is: to print the val without myInt.val
I tried to override toString()?!
public String toString(){
return ""+val;
}
and it works! But I want the return type to be int/Integer NOT String, and there is a compiler error
The return type is incompatible with Object.toString()"
when I change the return type to int. Is there a way to do that?
EDIT:
In Short:
Integer integer = new Integer(5);
int INT = integer;
System.out.println(INT);
So I want myClass "MyInt" works Like class "Integer"
so I can assign int val directly
MyInt myInt = new MyInt(5);
int INT = myInt; // I don't need to type "myInt.val"
System.out.println(INT);
This is wrong on a conceptual and code quality level.
The method is called toString().
Every Java programmer knows what this thing is supposed to do (to provide a string representation of the object you call it on).
Every Java programmer expects this method to return a String, and not an int.
Long story short: instead of overriding existing methods and totally changing their behavior (what is a super-bad idea by the way): simply add your own, new method and give that a reasonable name.
Finally: what you have in mind (changing the "contract" of methods) is most often a violation of the Liskov Substitution Principle. Meaning: don't do things because you could do them. Instead really learn and understand the concepts that you intend to use. What I am saying: proper inheritance in good OO designs is much more than putting some extends keyword somewhere; and some #Override in front of a method declaration.
You seem to have misunderstood what happens behind the scenes when you call this:
System.out.println(myInt);
The println method takes an Object argument and then calls the .toString() method on that object. The toString() method always returns a string. Therefore what you did (return a string) was correct.
Note that when you do this:
System.out.println(1);
then there is an overload of println specifically for int arguments. But you can't pass an Object to println and expect it to be treated as a primitive type.
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.