RederickDeathwill

The "new" keyword inside System.out.println example

May 26th, 2015
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. // The "new" keyword inside System.out.println example with comments, by Ericson Willians.
  2.  
  3. public class CustomClass {
  4.  
  5.     private String s; // Declares a private field of String type in CustomClass, accessible only from inside.
  6.    
  7.     public CustomClass(String s) { // Declares and initializes the constructor, which is void, and takes a String as an argument.
  8.         this.s = s; // Initializes the private String field with the argument given to the constructor.
  9.     }
  10.    
  11.     public String getString() { // Declares and initializes a public method to return the private String,
  12.         return this.s; // So that the outside world can access it.
  13.     }
  14.    
  15. }
  16.  
  17. public class Main {
  18.  
  19.     public static void main(String[] args) {
  20.        
  21.         System.out.println(new CustomClass("Hello World!").getString());
  22.        
  23.         // The "new" keyword returns an instance of the given class, which is initialized with its constructor.
  24.         // As soon as the CustomClass instance has been returned, it was possible to access its "getString()" method.
  25.         // Which returns the String object that I've passed to the constructor, "Hello World!".
  26.  
  27.     }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment