SHARE
TWEET

Untitled

a guest Feb 17th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Song {
  2.  
  3.     // Examples variables
  4.     private String songName;
  5.     private float songDurationTime;
  6.    
  7.     public Song(String songName, float songDurationTime) {
  8.         this.songName = songName;
  9.         this.songDurationTime = songDurationTime;
  10.     }
  11.    
  12.     // Comment out this method to see what it looks like with no overriding
  13.     @Override
  14.     public String toString() {
  15.         return "Song: " + songName + " Song Time: " + songDurationTime;
  16.     }
  17.    
  18.     public static void main(String[] args) {
  19.         // Construct a new song object with the name Jingle Bells and a duration of 30
  20.         Song jingleBells = new Song("Jingle Bells", 30f);
  21.        
  22.         // Calling the to String method -> Since we do not have an implementation for toString in our song class,
  23.         // it will grab it from the object class
  24.         // The object class toString() method looks like this below
  25.         /*
  26.         public String toString() {
  27.             return getClass().getName() + "@" + Integer.toHexString(hashCode());
  28.         }
  29.         */
  30.        
  31.         // Expected result: com.jb.song.Song@hashcode
  32.         // Printed result from console: com.jb.song.Song@7852e922
  33.         System.out.println(jingleBells.toString());
  34.        
  35.         // Now we create a toString() method in our song class. Notice how we have a @Override annotation. This means that this method
  36.         // will be called instead of the Object class method. This is what we call overriding a method.
  37.         // If we run the same toString method again...
  38.        
  39.        
  40.         // Expected result: Song Jingle Bells Song Time: 30
  41.         // Printed Result
  42.         System.out.println(jingleBells.toString());
  43.        
  44.     }
  45.    
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top