Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Understanding constructors

How constructors differ from methods

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 2

class Mammal {
       void getBirthInfo() {
               System.out.println("born alive.");
       }
}
class Platypus extends Mammal {
       void getBirthInfo() {
               System.out.println("hatch from eggs");
               System.out.print("a mammal normally is ");
               super.getBirthInfo();
       }
}


In the above program, the call to super.getBirthInfo() calls the overridden method of the Mammal superclass.

Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain. An example follows:

public class SuperClassDemo {
        SuperClassDemo() {}
}
class Child extends SuperClassDemo {
       Child() {
               super();
       }
}


In the above (and trivial!) example, the constructor Child() includes a call to super, which causes the class SuperClassDemo to be instantiated, in addition to the Child class.

Compiler-supplied code

The new Java programmer may stumble when the compiler automatically supplies code for constructors. This happens if you write a class with no constructors; the compiler will automatically supply a no-argument constructor for you. Thus, if you write:

public class Example {}


it is functionally equivalent to writing:

public class Example {
       Example() {}
}


The compiler also automatically supplies code when you do not use super (using zero or more parameters) as the first line of a constructor. In this case, the computer automatically inserts super. Thus, if you write:

public class TestConstructors {
       TestConstructors() {}
}


it is functionally equivalent to writing:

public class TestConstructors {
       TestConstructors() {
               super;
       }
}


The sharp-eyed beginner may wonder how the above program can call the parent class's constructor when TestConstructor is not extending any class. The answer is that Java extends the Object class when you do not explicitly extend a class. The compiler automatically supplies a no-argument constructor if no constructor is explicitly declared, and automatically supplies a no-argument super call when a constructor has no explicit call to super. So the following two code snippets are functionally equivalent:

public class Example {} 


and

public class Example {
       Example() {
             super;
       }
}


Inheritance

What is wrong with the following scenario? A lawyer is reading the will of A. Class. Members of the Class family are gathered around a large conference table, some sobbing gently. The lawyer reads, "I, A. Class, being of sound mind and body, leave all my constructors to my children."

The problem is that constructors cannot be inherited. Fortunately for the Class children, they will automatically inherit any of their parents' methods, so the Class children will not become totally destitute.

Remember, Java methods are inherited, constructors are not. Consider the following class:

public class Example {
        public void sayHi {
                system.out.println("Hi");
        }
        Example() {}
}
public class SubClass extends Example {
}


The SubClass class automatically inherits the sayHi method found in the parent class. However, the constructor Example() is not inherited by the SubClass.

Summarizing the differences

Just as the platypus differs from the typical mammal, so too do constructors differ from methods; specifically in their purpose, signature, and use of this and super. Additionally, constructors differ with respect to inheritance and compiler-supplied code. Keeping all these details straight can be a chore; the following table provides a convenient summary of the salient points. You can find more information regarding constructors and methods in the Resources section below.

About the author

Robert Nielsen is a Sun Certified Java 2 Programmer. He holds a master's degree in education, specializing in computer-assisted instruction, and has taught in the computer field for several years. He has also published computer-related articles in a variety of magazines.Table 1. Differences Between Constructors and Methods
Topic Constructors Methods
Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, native, static, or synchronized Can be abstract, final, native, static, or synchronized
Return type No return type, not even void void or a valid return type
Name Same name as the class (first letter is capitalized by convention) -- usually a noun Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this Refers to another constructor in the same class. If used, it must be the first line of the constructor Refers to an instance of the owning class. Cannot be used by static methods
super Calls the constructor of the parent class. If used, must be the first line of the constructor Calls an overridden method in the parent class
Inheritance Constructors are not inherited Methods are inherited
Compiler automatically supplies a default constructor If the class has no constructor, a no-argument constructor is automatically supplied Does not apply
Compiler automatically supplies a default call to the superclass constructor If the constructor makes no zero-or-more argument calls to super, a no-argument call to super is made Does not apply


  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (7)
Login
Forgot your account info?

A ThoughtBy Anonymous on September 2, 2009, 2:48 pmBased on your explanation it seems that a constructor is a very specialized method.

Reply | Read entire comment

Simple but more understandingBy Anonymous on August 17, 2009, 10:59 ambefore this... i learn java and not understand very well about constructor and method.. after i read your explanation.. it make me more understand. thank u........ sory!!!...

Reply | Read entire comment

well doneBy Anonymous on July 11, 2009, 9:54 amwell done

Reply | Read entire comment

excellentBy Anonymous on June 28, 2009, 9:22 amexcellent

Reply | Read entire comment

Constructor definitionBy Anonymous on April 23, 2009, 3:46 pmA constructor DO NOT create the object. It INITIALIZES the object after the creation or during the creation. The object is created by the new operator allocating...

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources