Basically this is what I am trying to achieve.
classname#address(?)[original toString()], object's name, object's age
#Override public String toString()
{
return String.format("%s , %s , %d", this.toString(), this.getName(),this.getAge());
}
Problem, toString() gets called recursively.
I can't call super.toString() because that's not what I want. I want 'this' to call the original toString().
This
this.super.toString()
doesn't work for obvious reasons.
I'm running out of steam, can this be done once a method gets overridden? I.e. call the original implementation ?
(my edit) Basically what I need is: override toString to display two properties of 'this' object, and I also want to have 'this' call the original toString.
This is not a project , or work. Just playing(learning) with Java language. Thanks
You're looking for super.toString().
Actually, I was trying to achieve the same thing, where super.toString() wasn't exactly what I wanted. I believe that this is not possible.
Specifically, I have a domain class in Groovy/Grails, and I wanted to override its toString() method to add some extra information:
class Child extends Parent {
public String toString() {
return super.toString(this) + extra_info // not possible!!!
}
}
This is not identical to return super.toString() + extra_info. In one case I get e.g.
com.example.domain.Parent : 15, extra_info. (Wrong. The instance is the same, but toString includes type information.)
In the other:
com.example.domain.Child : 15, extra_info. (Correct, but not possible.)
Related
This question already has answers here:
Can someone explain a void return type in Java?
(5 answers)
Closed 6 years ago.
I'm confused about "void",
as it pertains to methods.
I don't know what the distinction between two methods is when one has "void" and another doesn't.
For example, if I do:
Public meth (int amount)
{
amount = initial * interest;
return amount;
}
( not sure if it was right, or even valid, to take the name "amount" and name it the same thing as my formal parameter, but what makes sense here is that you're performing a calculation and returning the result)
Then, if I did something like:
Public void Testing (int array[])
{
//code that would modify the internals of an array
}
Would the second one have no "return" because it's more of a general method, that can be applied to any integer array, while the first one is about doing work on specific variables?
Would also appreciate one or two more examples of when I would or wouldn't be using "void" and "return".
One other thing that seems to confuse me is calling methods.
I know sometimes I'll do something like, for example, using the Testing method above,
Testing(ArrayName);
Other times, it will be like:
NameOfWhateverImApplyingMethodTo.MethodName();
And then there are times when things will be done properly by:
Thing1.MethodName(Thing2);
Which circumstances would I switch the syntax for method calls like this?
Java is case sensitive, so the modifier Public is invalid, use public
You can't define a method as public methodName(int a), only a constructor has this signature, a method must be public void methodName(<signature>) for methods that don't return anything or public <return type> methodName(<signature>) for methods that do.
Void basically means that the method will not return anything.
If you did
String name= "tim";
public void getName(){
return name;
}
This would result in an error, because the getName method is returning a string object called name, but the method declaration is saying I am returning nothing - because it is void.
Instead the method should be :
String name = "tim";
public String getName(){
return name;
}
Now when the method getName() is called it will return a string object "name" with "tim" inside of it :)
You might have void for a set method. So for example
String name = "tim";
public void setName(String newName){
this.name = newName;
}
When this method is called you would use setName("Andy"); and it would set the value of the name variable to be "Andy". Nothing is returned in this method, because it is setting something, but there is no need to send anything back, so we use void on the method declaration.
Hope this helps.
The method that has void as return type does not return anything. For example you want to set a field firstName in your class. You will write a setting method like
public void setFirstName(String n) {
this.firstName = n;
}
As you can see you are just setting a class variable and does not require to return anything.
If you dont use void then you have to provide a return type for method. Like if you wish to write a getter for above variable as:
public String getFirstName() {
return this.firstName;
}
Once you provide a return type, you will have to return a value of that type otherwise your code will not compile.
Calling a method can be done based on where you are calling it from and what modifier is used:
If you are calling the method from the same class then you can simply write firstName = getFirstName()
If you are calling the method from another class then you require object of method's class as qualifier like personObject.getFirstName()
If you are calling a static method then you require class name as qualifier like Person.getFirstName();
Return type is what you get out of it. When you call it, what are you hoping to get back? For instance, if the method gets the average of two numbers, then you're expecting a number back, so the return type will be a number type, like "int" (integer).
You can see what it should be using that logic or by looking in the method for the word return - what comes after return is what is returned, and its type should be declared in the method (e.g. if it says "return 4;" it's returning an int, and should be e.g. public int getFour()
You also asked about e.g. testing() vs testing(word)
I remember having the same difficulty. The distinction between the two also relates to the method declaration line. I'll illustrate.
public String testing(){
return "a word";
}
Calling this method by doing "System.out.println(testing());" should print "a word". Calling this method by doing "System.out.println(testing("a word"));" will give you an issue - this is because when you call testing, it looks at the appropriate method: one in the right class, with the right return type and with the right arguments/parameters. If you're calling testing("a word"), that means you're using a String as an argument (because "a word" is a string), and so it tries to use the testing(String aString) method - which doesn't exist.
So you use empty brackets when the method takes no input, and you put stuff in brackets when the method expects stuff. This should be less confusing than it sounds, because it's usually logical - if you want to call a method that returns an average, you need to ask yourself "Average of what?" You'd probably need to supply it with the values you want the average of.
Moving on: (a) testing() versus(b) AClass.testing() versus(c) aclass.testing() -
In (a), there's no class specified. Therefore, if you call it from that class, Java can guess which class: this one, and it'll work. From any other class, it won't know what you're talking about, and might even insult you.
In (b), you're specifying a class in general - therefore it'll know what class to find it in - and it'll work if it's a "static method". *[see bottom]
In (c), you're specifying an instance of AClass you want to run "testing()" on*.
For instance, imagine you've created a class called Business. You make a hundred Business objects by specifying for each a name, number, address.
e.g.
Business b = new Business(name, number, address);
Then in the Business class you have a method "getName()". This method takes no argument - you could see that the brackets are empty - so if, from another class, you call "Business.getName()", how could it know which name you want? You've just made a hundred businesses!
It simply can't. Therefore, for such a method, you'd call "b.getName()" (b being the Business we created above) and it would get the name for this instance of a Business - namely, b.
I'm happy to help, so if you're confused about any particular parts of what I just wrote please let me know and I'll try to elaborate!
edit: A bit on static methods:
Static methods don't belong to an instance of the class. getName(), for example, would get the name of this Business - ie, this instance of the Business class. But let's say that in the Business class you made a method that took the first letter of each word in a String and transformed it to uppercase - like if you wanted to make the business names look more professional when you printed them out.
public static String stringToUpperCase(String aString){
aString = aString.substring(0, 1).toUpperCase() + aString.substring(1);
return aString;
}
And to use that, you change the getName() method from:
public String getName(){
return name;
}
to
public String getName(){
return stringToUpperCase(name);
}
The new method is used here to make the name have an uppercase first letter - but that is the extent of its involvement with the Business class. You notice it doesn't ask for information about the name, address, or number for a particular business. It just takes a string you give it, does something to it, and gives it back. It doesn't matter whether you have no Businesses or a hundred.
To call this method, you'd use:
System.out.println(Business.stringToUpperCase("hello"));
This would print Hello.
If it were not a static method, you'd have to make a new Business first:
Business b = new Business("aName", "aNumber", "anAddress");
System.out.println(b.stringToUpperCase("hello"));
And if the method did need access to more Business-instance information (like a business's name number or address) it wouldn't be able to be an instance variable.
The first example, a method without a return type at all, is a constructor; used when an instance is created with new. However, you can't return a value from a constructor. Something like,
this.amount = initial * interest; // return amount;
Sets the field amount to initial * interest.
for some reason when I run my app, instead of getting the name of the lecture, I get a bunch of random characters that show up. I'm not sure why though. Thanks in advance!
public Lecture(String lecturename) {
this.lecturename = lecturename;
listofwork = new ArrayList<Work>();
}
public String toString(Lecture lecture) {
return lecture.lecturename;
}
/////////// IN ANOTHER ACTIVITY /////////////////////
Lecture test = new Lecture("TEST");
Toast.makeText(getApplicationContext(), test.toString(), Toast.LENGTH_LONG).show();
And instead of getting a toast saying "TEST", I get whatsmymark.Lecture#41abcf8. I have a feeling its returning the actual lecture object rather than the string. However, I can't find out why cause the code is so simple.
You are writing a toString that takes a Lecture as an argument, and calling toString() that takes no arguments. If you change your method definition to have no args, you will override the Object.toString() correctly.
public String toString() {
return this.lecturename;
}
If you do not want to change your method definition for some reason, your other option is to call your version explicitly, but I am sure you will agree this looks a little redundant.
Lecture test = new Lecture("TEST");
Toast.makeText(getApplicationContext(), test.toString(test), Toast.LENGTH_LONG).show();
When you do test.toString(), you're printing the *test object itself *, not a string representing the object. Because you didn't override Object#toString() (you overloaded it instead), your object inherits this implementation:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
And that's probably not what you wanted.
What you'll need to do is put the toString() method you have inside the Lecture class, and remove its formal parameter. Then it should work.
A good idea is to put the #Override annotation on methods you intended to override. This way if you accidentally mess up the compiler should emit an error/warning letting you know.
you may want to change your code like this
public Lecture(String lecturename) {
this.lecturename = lecturename;
listofwork = new ArrayList<Work>();
public String toString() {
return this.lecturename;
}
}
I have defined the arraylist as follows:
ArrayList<Node> nodes = new ArrayList<Node>();
Where Node is a class which has one character data type for storing a single character.
The output is showing some garbage value instead of printing characters:
Here is a code snippet. Can anyone explain why?
for(Node d : nodes){
System.out.println(d);
}
Your Node class does not override the toString method. That's why the default implementation is called, producing what looks like "garbage".
In your Node class add a toString method that takes no parameters and returns a String that describes the content of your node in an application-specific way. This will fix the output.
System.out.println(d) is equivalent to System.out.println(d.toString())
If you did'nt redefine the method toString() in your Node classe, java uses the method toString() of the class that your object have inherited.
By default, all classes inherited the superclass Object where the toString() method is defined as :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why it looks like "garbage"
Unless you subclass ArrayList and override the toString method, simply calling println on the ArrayList will print the address of the object reference (this is the garbage you're seeing), not the actual contents of the arraylist. To get your desired result, use:
System.out.println(Arrays.toString(nodes.toArray());
BTW - the other folks are correct, you'll also need to override the toString() method of your node class (in general, it is always a best practice to override the toString() method of any class you design).
To address the problem you mentioned in your comment below:
public String toString(){
return Character.toString(label);
}
I have two classes :
import android.cla;
public class CW {
public static void main(String [] args){
System.out.println(new cla());
}
}
public class Cl {
#Override
public String toString(){
return "LOL";
}
}
In the first class I'm calling the objects toString() method, which has been overriden and printing it to console. It clearly returns "LOL";
I have two questions :
Is it possible to return data while instantiating like this (new cla()) without overriding the objects toString() method; and
What is the proper term for instantiating classes like this (new cla()), that's without declaration like : Object l = new cla()
Thanks. Please correct me on the proper terms.
1 - No it isn't. A 'constructor' is a special method on the class that always returns an object instance of the class. The whole point of the constructor is to return the object. So no, it can't return anything else.
1a - The reason that System.out.println calls the toString method is because you are asking it to print out that object to the screen, and the toString method is the method chosen by the authors of println (and the Java language in general) to give a string representation of the object.
2 - That way of writing isn't really called anything. It's just an expression that you're passing as an 'actual parameter' to the println method. True, it's an expression that instantiates a new object, but it's no different to println("a string"). You could call it an anonymous object if you really wanted to.
2a - (old answer that doesn't actually answer your question but I'll keep it here) That's just called 'using a less derived reference† to a class'. Beware you can only call methods on the type of the reference, so if you added extra methods to your Cl class you couldn't call them from an Object reference. Look into Liskov substitution principle.
† 'less derived' or 'supertype' or 'superclass' or 'more general class' etc...
I have this very long exercise and I came a cross a problem in each sub class.
The problem says and I have no idea what mistake I've made while writing.
If you could check the 4 toString methods I would be much apprecaited .
The code is here: http://paste.org/pastebin/view/39488
I know I should past the code here but it is very long and I'm not able to organize it well.
toString() in Shape cannot override toString() in java.lang.Object; attempting to use incompatible return type
toString() in Square cannot override toString() in java.lang.Object; attempting to use incompatible return type
`
toString() in Sphere cannot override toString() in java.lang.Object; attempting to use incompatible return type
toString() in Cube cannot override toString() in java.lang.Object; attempting to use incompatible return type
thanks
You need to change the return type of the function to String and return the text instead of writing it to System.out.
public String toString() {
return "(" + super.getX() + ", " +
super.getY() +") " + "side: " + super.getDimension1();
}
EDIT: If you want to have a method that outputs the object directly to System.out in textual form, you'll need to call it something else than toString(). This is because toString() is a method belonging to java.lang.Object which all Java classes automatically extend.
toString() has to return String not void.
// false
public abstract void toString();
// right
public abstract String toString();
Note: You should not print (System.out) in the toString() method. You should rather return a String represenation of the object.
because you try to override it with a void return type. toString should return a String.
It should return a string and not void.
public abstract String toString()
toString() is implemented in Object class and every class extends it. This method is in every class and we can't have two method with same signature but different return type.
As toString() is already there with return type String, we can't have one more toString() with any other return type.