• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

My First Program: Output ---> Frog@360be0 ?

 
Rob Chong
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my first post to this site. Please bear with me.I have trouble to find out why the program I have written has produce an output of Frog@360be0. Can anyone please point to where I got it.

class Amphibian {
public void sound () { System.out.println("Croak...");}
static void makeSound(Amphibian a) {
a.sound();
}
public void populate() {
System.out.println("Populating...");
}
static void produce(Amphibian a) {
a.populate();
}

}
public class Frog extends Amphibian {
public static void main(String [] args) {
Frog croak = new Frog();
Amphibian.makeSound(croak);
System.out.println(croak);
Amphibian.produce(croak);
System.out.println(croak);
}
}
Output:
Croak...
Frog@360be0
Populating...
Frog@360be0
Press any key to continue . . .
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

When you call System.out.println(X), where 'X' is any object, Java calls the method "toString()" on that object, which returns a String; that String is then displayed.

Your Frog class doesn't define a toString() method, so it inherits the one from java.lang.Object. That method -- Object.toString() -- returns the name of the class, an '@' character, and the value returned by hashCode().

So the Frog@28876 you're seeing is just what Object.toString() returns.

Now, if you want something else to be printed -- like, say, "I'm a Frog", then you just have to define toString() in your Frog class, like this:



Now printing a Frog object will cause "I'm a Frog" to be displayed.
 
Rob Chong
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your reply. I've reworked my codes and try to demonstrate how overriding methods and upcasting can be performed. What I am not sure is whether my codes comply with the rules of overriding methods and upcasting.

Here is my codes:

class Amphibian {
public void sound () {}
static void makeSound(Amphibian a) { a.sound();}
public void populate() {}
static void produce(Amphibian a) {a.populate(); }

}
public class Frog2 extends Amphibian {
public void sound() {
System.out.println("I can croak.");
}
public void populate() {
System.out.println("We have populated.");
}

public static void main(String [] args) {
Frog2 croak = new Frog2();
Amphibian.makeSound(croak);
Amphibian.produce(croak);

}
}
/*
Ouput:
I can croak.
We have populated.
Press any key to continue . . .
*/
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic