Java Constructors generally.

Java Constructors generally

  • A constructor is a special method with the same name as its class and has no return.
  • A constructor is called by the Java system when a new class instance is created (an object).
  • This gives the class an opportunity to set up initials for use during the object's lifetime.
  • A constructor can accept arguments and can be overloaded as other methods.
  • Constructors are not, however, inherited or overrided like other methods.
  • The default constructor is the no-argument constructor automatically generated unless you define another constructor. However, if you define at least one constructor, the default constructor is not generated.
    Constructor example:
    public class Person {
      private int age;
      private String name="Nobody";
    // Constructor with two parameters
    // As this constructor is created - 
    // no default constructor will be generated  
      public Person(int age, String name) {
        this.age = age; = name;
      public int getAge() {
        return age;
      public void setAge(int age) {
        this.age = age;
      public String getName() {
        return name;
      public void setName(String name) { = name;
       public static void main(String args[]) {
         Person ricard= new Person(23,"Ricard");
         System.out.println("First person is called "
                 +ricard.getName()+" and is "
                 +ricard.getAge()+" years");
    The result of this is:
    First person is called Ricard and is 23 years
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.