Quick question about the toString() Method
Here are two very simple classes I made:
***********************************************************
public class Animal{
private String type;
public Animal(String aType){
type = aType;
}
public String toSring(){
return "This is a " + type;
}
}
**************************************************************
public class Test {
public static void main (String[]args) {
Animal aAnimal = new Animal("An Animal");
System.out.println(aAnimal.toString());
}
}
****************************************************************
When I compile and run I get: Animal@&$*&@ and not "An Animal" how come?
Re: Quick question about the toString() Method
That's what the default "toString()" method inherited from the Object class
produces. To override that, you would have to declare a method called
"toString()", which I don't see there. You do have one called "toSring()",
but you didn't call that.
PC2
"John" <goreckijohn@hotmail.com> wrote in message
news:3b51cbe8$1@news.devx.com...
>
> Here are two very simple classes I made:
>
> ***********************************************************
>
> public class Animal{
>
> private String type;
>
> public Animal(String aType){
> type = aType
> }
>
> public String toSring(){
> return "This is a " + type;
> }
>
> }
>
> **************************************************************
>
> public class Test {
>
> public static void main (String[]args) {
>
> Animal aAnimal = new Animal("An Animal");
> System.out.println(aAnimal.toString());
>
> }
> }
>
> ****************************************************************
>
> When I compile and run I get: Animal@&$*&@ and not "An Animal" how come?
Re: Quick question about the toString() Method
"John" <goreckijohn@hotmail.com> wrote:
>
>Here are two very simple classes I made:
>
>***********************************************************
>
>public class Animal{
>
>private String type;
>
>public Animal(String aType){
> type = aType;
>}
>
>public String toSring(){
> return "This is a " + type;
>}
>
>}
>
>**************************************************************
>
>public class Test {
>
>public static void main (String[]args) {
>
> Animal aAnimal = new Animal("An Animal");
> System.out.println(aAnimal.toString());
>
> }
>}
>
>****************************************************************
>
>When I compile and run I get: Animal@&$*&@ and not "An Animal" how come?
the method "tostring" of a class returns "the class`s name@hexcode".
when i use the following code
class Number
{
private int num;
Number(int anum)
{
this.num = anum;
}
public String toSring()
{
return "the number is "+num;
}
}
public class Test
{
public static void main (String[]args)
{
Number newnum=new Number(30);
System.out.println(newnum.toString());
}
}
i get Number@256a7c,the reason is the same.
Re: Quick question about the toString() Method
You aren't overriding 'toString' cause you spelt it wrong.