I am using Eclipse Build id: 20120614-1722.
I have an object class called "TOY1" and a function toString() within it. I previously know that when I call the
System.out.println(TOY1);
It should return the address. However, and for some reason it is returning the toString() declared for my object without me specifying the #Override notation.
Is it safe to keep it that way? Or is this a new feature implemented in the specific build I have.
Thanks
EDIT
As asked this is part of my code:
public class TOY1 {
//irrelevant declarations
public String toString() {
String data;
data="Manufacturer=";
data+=manufact;
data+="DOP:";
data+=date_of_production;
return data;
}
}
When declaring TOY1_instance of TOY1 and then printing out using the System.out.printIn(TOY1_instance)
I am getting the actual data as opposed to some junk address.
My question is where did I override it no warning was shown and no extension overrides this class.
System.out.println(obj); is calling obj.toString() internally. It happens that the default implementation of toString(), if you don't override it, returns some address-like value.
You can omit #Override annotation, but it's safer to use it. It becomes especially useful when you think you are overriding while you aren't because of tiny difference in signature. E.g.:
#Override
public String tostring() //...
won't compile. Even more common mistake is wrong equals():
#Override
public boolean equals(TOY1 obj) //...
Do you see why? Without #Override it's very easy to miss such a tremendous bug.
#Override annotation is just optional,
code works the same with and without it.
But it's a matter of good taste, to use it. It clearly shows what's going on - that you redefine method from super-class or implement method from interface.
And as Tamasz mentioned - it's impossible to annotate with #Override method that actually isn't overriding anything. So it can save you sometimes.
It would always run the closest toString() instance method even if #Override is not specified. To be on the safer side, or to compile quickly and effeciently, you should include #Override at the top
#Override annotation is just for compilers, and JVM does not care about it.
See definition of Override annotation here:
#Target(value=METHOD)
#Retention(value=SOURCE)
public #interface Override
As you can see in the declaration, it is only retained in the source and not in the class file.
OK let me get it clear. So, your over-ridden function is still called but the issue is why is it called even when #override is not used? If that is the case, then this annotation is simply for the compiler to check whether you have actually overriden the function or not. It should not affect the logic of program as such. Also, please post code if you want specific answer.
Actually, System.out.println() can deal with several types of parameters, and one of them is reference to a String.
Please refer this URL
Related
I have a class and it has multiple subclasses which each implement their own methods. Some of these subclasses have common method which I need to call. Is there a way in java to know if the object has a method (without using instanceof)?
This probably points to a design flaw, but you could always use reflection to check if a method exists:
public static boolean hasMethod(Object obj, String methodName) {
return Arrays.stream(obj.getClass().getMethods())
.anyMatch(m -> m.getName().equals(methodName));
}
This, of course, could be refined to include the method's signature too, but the basic idea remains the same.
I've seen that in Android, sometimes when you override a method, it always come with a call to the super class, and every once in a while, some of you can't remove this call, because the IDE show's a compile time error. So that question is, Is it possible to enforce a call to a method inside of another? And if it is, how do I do that?
Youn can use the android support annotations for this. First you need to use the support annotations in your project:
dependencies {
compile 'com.android.support:support-annotations:22.2.0'
}
Use the #CallSuper annotation.
You can write your own annotation processor for this purpose to make customs behaviors
See more:
http://tools.android.com/tech-docs/support-annotations
https://netbeans.org/kb/docs/java/annotations-custom.html
I assume you mean you get a runtime exception and a warning in your IDE. There is no way to enforce at compile time that you call super.method() when you override method.
One thing you can do is flip a boolean to true in the superclass method.
public abstract class AbstractClass {
private boolean superCalled = false;
public void foo() { superCalled = true; }
void bar() {
foo();
if (!superCalled)
throw new IllegalStateException("You did not invoke super.foo()");
}
}
Thanks to #VinceEmigh for pointing out that onCreate works in this way by setting a boolean called mCall to true. Here is the code.
This works in android because you should not call onCreate directly - it is the android system, not you, that determines when onCreate is called. The writers of the android system can just ensure that the boolean is always checked after every call.
Well, that call to super is to utilize inheritance. It lets you get away with that call so that you don't have to implement everything that the method with the same name in your super class has already implemented. Which is quite great.
About calling another method from inside a method. You are always going it in some form or the other. Functions can have helper methods; even calling a mere constructor can be called calling a method from inside a method.
I used a method that took a String and I wanted to pass a primitive boolean. I expect it to take that boolean and convert it to a String containing either "true" or "false".
Assume the following method:
public void method(String input) { ... }
I first tried something like this:
boolean myBoolean = true;
method(myBoolean.toString());
This gave me an error during compilation. But then when I added following additional overloaded method, this worked again:
public void method(Boolean input) {
method(input);
}
I was confused to discover that in that case, calling method(myBoolean) worked just fine.
Why is this?
First thing to understand is that primitives do not have methods. At least not as of date, and might change with implementation of Project Valhalla. To be able to call the toString() on it, you will first require to box it either by autoboxing or by wrapping it explicitly.
Given a method public void takeString(String input) {}:
takeString(true) will fail, although
takeString(""+true) will work, as it is equivalent to
takeString(""+Boolean.valueOf(true).toString()), which works.
takeString(Boolean.valueOf(true).toString()) will work as well, but note that
takeString(Boolean.valueOf(true)) will fail again for the same reason as in (1).
It might be curious that in case (2), it was able to apply autoboxing and implicitly call the toString(), while it was not able to do so for (1).
But there is good reason for it, as in the case of (2), it is clear to the compiler that the method signature will have a parameter type of String, so it can do the needed implicit conversions. While for (1), it would be dangerous to do so given that we can have multiple overloaded versions of takeString. It just makes the compiler's job simpler, and avoids issues when the overloaded version would be added later on. It is safer to fail on (2).
Example, we do not want logic to suddenly change because we add following method: public void takeString(boolean input) {}.
Possibly you could consider adding following method:
public void takeString(Boolean b) {
takeString(b.toString());
}
The intent of "conversion-only" is clear here, and will reduce the chance of adding in additional unintended logic.
In that case, it might also be wiser to provide an overloaded version for the native boolean parameter to avoid surprises later on as the API evolves.
Then all your cases, except true.toString() will work. Seems like a case to ask to implement conversions in Java, the way we have them in Scala. That will avoid a lot of overload boilerplate.
Primitive types (boolean for example) do not have methods. That is why an error occured when you tried boolean.toString(). Wrapper classes than though (Boolean.toString() for example).
Now for the method, if your method is like this:
public void method(String s)
then you must have made another method like this:
public void method(boolean b)
to be able to perform method(boolean). Without the method(boolean b), your compiler would say method cannot be applied to boolean or something along those lines.
I am refactoring a class to use a builder with a private constructor instead of public constructors. I want to have the old, deprecated, public constructors use the builder as shown below. (this is an example of the behavior I am try to achieve)
// old public construcor
#Deprecated
public MyClazz(){
return new MyClazzBuilder().Build();
}
This give a "Cannot return a value from a method with void result type"
Is this type of functionality possible in Java? How could this be achieved?
Update: This code is part of a distributed jar, deleting the old constructors is not an option because I need to maintain backwards compatibility
No. Constructors operate on an object, they don't return it. [footnote 1]
One way to get this sort of functionality is with an init() method.
#Deprecated
public MyClazz() {
init();
}
public void init() {
// do the actual work
}
Now your builder can call the same init() method to avoid having the code in two places.
Because you are keeping the deprecated signatures around, it's hard to avoid splitting the logic for preparing an instance into multiple places. That's not ideal, but it's the price of deprecation and maintaining backwards compatibility.
[footnote 1] The lifecycle of a java object is that first the object memory is allocated, but all the fields have junk content. Next a constructor is run on the memory to get it into a consistent state by changing all those meaningless values into real values. Note that the memory the constructor works on is already there, so you can never substitute another object in place of the one being constructed. A return value from a constructor would be exactly this sort of substitution, which is not supported by the language. If that trick is needed use a factory/builder instead of a constructor -- constructors can never do that.
Constructors don't return values. Notice how there is no "declared" return type in a constructor signature. You have a few options:
1) Mark the constructor private and resolve compilation errors immediately
2) Deprecate the constructor, and leave the original implementation there.
I recommend number 2. What you have done is deprecate a constructor, and then changed the implementation. That is not how deprecation works.
Due to the use of Generics in Java I ended up in having to implement a function having Void as return type:
public Void doSomething() {
//...
}
and the compiler demands that I return something. For now I'm just returning null, but I'm wondering if that is good coding practice...
I'm asking about Void, not void. The class Void, not the reserved keyword void.
I've also tried Void.class, void, Void.TYPE, new Void(), no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See this answer for details)
So what am I supposed to return if the return type of a function is Void?
What's the general use of the Void class?
So what am I supposed to return if the return type of a function has to be Void?
Use return null. Void can't be instantiated and is merely a placeholder for the Class<T> type of void.
What's the point of Void?
As noted above, it's a placeholder. Void is what you'll get back if you, for example, use reflection to look at a method with a return type of void. (Technically, you'll get back Class<Void>.) It has other assorted uses along these lines, like if you want to parameterize a Callable<T>.
Due to the use of generics in Java I ended up in having to implement this function
I'd say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there's a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I'm a little suspicious, since this only came up "due to the use of generics".
There's no way to instantiate a Void, so the only thing you can return is null.
return null is the way to go.
To make clear why the other suggestions you gave don't work:
Void.class and Void.TYPE point to the same object and are of type Class<Void>, not of Void.
That is why you can't return those values. new Void() would be of type Void but that constructor doesn't exist. In fact, Void has no public constructors and so cannot be instantiated: You can never have any object of type Void except for the polymorphic null.
Hope this helps! :-)
If, for obscure reasons, you MUST use this type, then indeed returning null seems to be a sensible option, since I suppose return value will not be used anyway.
The compiler will force you to return something anyway.
And this class doesn't seem to have a public constructor so new Void() is not possible.
just like this.
public Class TestClass {
public void testMethod () {
return;
}
}