Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Song {
- // Examples variables
- private String songName;
- private float songDurationTime;
- public Song(String songName, float songDurationTime) {
- this.songName = songName;
- this.songDurationTime = songDurationTime;
- }
- // Comment out this method to see what it looks like with no overriding
- @Override
- public String toString() {
- return "Song: " + songName + " Song Time: " + songDurationTime;
- }
- public static void main(String[] args) {
- // Construct a new song object with the name Jingle Bells and a duration of 30
- Song jingleBells = new Song("Jingle Bells", 30f);
- // Calling the to String method -> Since we do not have an implementation for toString in our song class,
- // it will grab it from the object class
- // The object class toString() method looks like this below
- /*
- public String toString() {
- return getClass().getName() + "@" + Integer.toHexString(hashCode());
- }
- */
- // Expected result: com.jb.song.Song@hashcode
- // Printed result from console: com.jb.song.Song@7852e922
- System.out.println(jingleBells.toString());
- // Now we create a toString() method in our song class. Notice how we have a @Override annotation. This means that this method
- // will be called instead of the Object class method. This is what we call overriding a method.
- // If we run the same toString method again...
- // Expected result: Song Jingle Bells Song Time: 30
- // Printed Result
- System.out.println(jingleBells.toString());
- }
- }
Add Comment
Please, Sign In to add comment