Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Java Constructor Overloading

class Main {

  String fruit;

  // constructor with no parameter
  Main() {
    this.fruit = "Banana";
  }

  // constructor with a single parameter
  Main(String fruit) {
    this.fruit = fruit;
  }

  public void getName() {
    System.out.println("Fruit: " + this.fruit);
  }

  public static void main(String[] args) {

    // call constructor with no parameter
    Main obj1 = new Main();

    // call constructor with a single parameter
    Main obj2 = new Main("Apple");

    obj1.getName();
    obj2.getName();
  }
}
Source by softhunt.net #
 
PREVIOUS NEXT
Tagged: #Java #Constructor #Overloading
ADD COMMENT
Topic
Name
2+6 =