Another Constructor Overloading Example


The following program shows another example of constructors:

Person.java (constructor overloading)
// Java program to overload constructors  
public class Person {
  // two member variables
  String name = "Pikachu";
  int     age = 10;

  // the driver method
  public static void main( String args[ ] ) {
    Person p1 = new Person( );
    Person p2 = new Person( "Ash", 13 );
    p1.display( );
  }

  // a default constructor
  Person( ) { }

  // a two-argument constructor
  Person( String n, int a ) { name = n; age  = a; }

  // a method
  void display( ) { System.out.println( name + " " + age ); }
}
Output:           Result:

Review: Constructors vs Methods
    Which statement is NOT true about a Jave constructor?

      A constructor must have a return type.
      The constructor is invoked implicitly.
      The constructor name must be the same as the class name.
      The Java compiler provides a default constructor if you do not have any constructor in a class.
        Result:




      Why are green beans the most Zen of all vegetables?    
      Because they’ve found their inner peas.