GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||
GeezerVison is showing jenkov.com — Java Constructors Java Language
Java Constructors
A Java constructor is special method that is called when an object is instantiated. In other words, when you
use the Here is a simple example that creates an object, which results in the class constructor being called: MyClass myClassObj = new MyClass();
This example results in a new A Java class constructor initializes instances (objects) of that class. Typically, the constructor initializes the fields of the object that need initialization. Java constructors can also take parameters, so fields can be initialized in the object at creation time. Defining a Constructor in JavaHere is a simple Java constructor declaration example. The example shows a very simple Java class with a single constructor. public class MyClass {
public MyClass() {
}
}
The constructor is this part: public MyClass() {
}
The first part of a Java constructor declaration is an access modifier. The access modifier have the same meanings as for methods and fields. They determine what classes can access (call) the constructor. Access modifiers are covered in more detail in my Java access modifiers tutorial. The second part of a Java constructor declaration is the name of the class the constructor belongs to. Using the class name for the constructor signals to the Java compiler that this is a constructor. Also notice that the constructor has no return type, like other methods have.
The third part of a Java constructor declaration is a list of parameters the constructor can take. The constructor
parameters are declared inside the parentheses
The fourth part of a Java constructor declaration is the body of the constructor. The body of the constructor is
defined inside the curly brackets Constructor Overloading - Multiple Constructors for a Java ClassA class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need. When a Java class contains multiple constructors, we say that the constructor is overloaded (comes in multiple versions). This is what constructor overloading means, that a Java class contains multiple constructors. Here is a Java constructor overloading example: public class MyClass {
private int number = 0;
public MyClass() {
}
public MyClass(int theNumber) {
this.number = theNumber;
}
}
The Java class above contains two constructors. The first constructor is a no-arg constructor, meaning it
takes no parameters (no arguments). The second constructor takes an
The keyword Default, no-arg ConstructorYou don't have to define a constructor for a class, but if you don't define any constructor, the Java compiler will insert a default, no-argument constructor for you. Thus, once the class is compiled it will always at least have a no-argument constructor. If you do define a constructor for your class, then the Java compiler will not insert the default no-argument constructor into your class. Constructor ParametersAs you have already seen, it is possible for a Java constructor to take parameters. These parameters can then be used to initialize the internal state (fields) of the newly created object. Here is an example: public class Employee {
private String firstName = null;
private String lastName = null;
private int birthYear = 0;
public Employee(String first,
String last,
int year ) {
firstName = first;
lastName = last;
birthYear = year;
}
}
In this example the Java constructor declaration is marked in bold. As you can see, three parameters
are declared: The line breaks after each parameter are optional. The Java compiler ignores line breaks here. You can also write the parameter declaration in a single line if you want, like this: public Employee(String first, String last, int year ) {
firstName = first;
lastName = last;
birthYear = year;
}
To call this constructor that takes three parameters, you would instantiate an Employee employee = new Employee("Jack", "Daniels", 2000);
The parameters are passed to the constructor inside the parentheses after the class name on the right side of the equal sign. The object is then created, and the constructor executed. After execution of the above constructor, the fields initialized by the constructor will have the values of the parameters passed to the constructor. A Java constructor parameter can have the same name as a field. If a constructor parameter has the same name as a field, the Java compiler has problems knowing which you refer to. By default, if a parameter (or local variable) has the same name as a field in the same class, the parameter (or local variable) "shadows" for the field. Look at this constructor example: public class Employee {
private String firstName = null;
private String lastName = null;
private int birthYear = 0;
public Employee(String firstName,
String lastName,
int birthYear ) {
firstName = firstName;
lastName = lastName;
birthYear = birthYear;
}
}
Inside the constructor of the Employee class the
To signal to the Java compiler that you mean the fields of the Employee class and not the parameters, put the
public class Employee {
private String firstName = null;
private String lastName = null;
private int birthYear = 0;
public Employee(String firstName,
String lastName,
int birthYear ) {
this.firstName = firstName;
this.lastName = lastName;
this.birthYear = birthYear;
}
}
Now the Employee fields are correctly initialized inside the constructor. Calling a ConstructorYou call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass();
This example invokes (calls) the no-argument constructor for In case you want to pass parameters to the constructor, you include the parameters between the parentheses after the class name, like this: MyClass myClassVar = new MyClass(1975);
This example passes one parameter to the Calling a Constructor From a Constructor
In Java it is possible to call a constructor from inside another constructor. When you call a constructor from
inside another constructor, you use the public class Employee {
private String firstName = null;
private String lastName = null;
private int birthYear = 0;
public Employee(String first,
String last,
int year ) {
firstName = first;
lastName = last;
birthYear = year;
}
public Employee(String first, String last){
this(first, last, -1);
}
}
Notice the second constructor definition. Inside the body of the constructor you find this Java statement: this(first, last, -1);
The Calling Constructors in SuperclassesIn Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. Inheritance is covered in more detail in my tutorial about inheritance in Java. A class that extends another class does not inherit its constructors. However, the subclass must call a constructor in the superclass inside of its the subclass constructors! If a subclass calls another constructor within itself, then the called constructor must call the superclass constructor. Look at the following two Java classes. The class Car extends (inherits from) the class Vehicle. public class Vehicle {
private String regNo = null;
public Vehicle(String no) {
this.regNo = no;
}
}
public class Car extends Vehicle {
private String brand = null;
public Car(String br, String no) {
super(no);
this.brand = br;
}
}
Notice the constructor in the Car class. It calls the constructor in the superclass using this Java statement: super(no);
Using the keyword Java Constructor Access ModifiersThe access modifier of a constructor determines what classes in your application that are allowed to call that constructor. The access modifiers are explained in more detail in the text on Java access modifiers.
For instance, if a constructor is declared A class can have multiple constructors, and each constructor can have its own access modifier. Thus, some constructors may be available to all classes in your application, while other constructors are only available to classes in the same package, subclasses, or even only to the class itself (private constructors). Throwing Exceptions From a ConstructorIt is possible to throw an exception from a Java constructor. Here is an example of a Java class with a constructor that can throw an exception: public class Car {
public Car(String brand) throws Exception {
if(brand == null) {
throw new Exception("The brand parameter cannot be null!");
}
}
}
Notice the
Here is an example of calling the Car car = null;
try{
car = new Car("Mercedes");
//do something with car object
} catch(Exception e) {
// handle exception
}
In case an exception is thrown from the Making a constructor throw an exception can be a good idea if you want to prevent an object of the given class to be created in an invalid state. Typically it is the input parameters to the constructor that may cause the object to be invalid. If the constructor detects an invalid input parameter, it can throw an exception and prevent the assignment of the object to any variable. Next: Java Packages
Close TOC
All Trails Trail TOC Page TOC Previous Next | ||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | ||||||