Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The "new" keyword inside System.out.println example with comments, by Ericson Willians.
- public class CustomClass {
- private String s; // Declares a private field of String type in CustomClass, accessible only from inside.
- public CustomClass(String s) { // Declares and initializes the constructor, which is void, and takes a String as an argument.
- this.s = s; // Initializes the private String field with the argument given to the constructor.
- }
- public String getString() { // Declares and initializes a public method to return the private String,
- return this.s; // So that the outside world can access it.
- }
- }
- public class Main {
- public static void main(String[] args) {
- System.out.println(new CustomClass("Hello World!").getString());
- // The "new" keyword returns an instance of the given class, which is initialized with its constructor.
- // As soon as the CustomClass instance has been returned, it was possible to access its "getString()" method.
- // Which returns the String object that I've passed to the constructor, "Hello World!".
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment