Constructors
Constructors are special methods that are used to instantiate(construct) the object. Constructors have certain characteristics.
Constructor Characteristics
1. Have the same name as the class.
2. Have no return type.
3. A default, no-argument constructor is automatically provided by the compiler if you do not create one.
4. Constructors can be overloaded
5. Needs to be declared as public to be available outside the package to other classes
public class Socket{
}
The socket
class have a default constructor, since we did not create a custom one. The default constructor will be as follows
public Socket() {
}
Socket
class default constructor.
Calling the Constructor
The constructor is called to create a new object from the class using the new
operator. This creates a new object called socket
from the Socket
class.
In Java the convention is usually to name the new object with the same name as the class but start the name with a lowercase letter.
Custom Constructor
The following defines a custom constructor for the Socket
class. The consturctor takes in a single parameter url
of type String
.
public class Socket{
public Socket(String url) {
}
}
When you invoke the consturctor, the arguments used must match the declaration's parameters in type and order.
We can create a new socket object by passing the url
argument String
as follows
Socket socket = new Socket("http://chat.peruzal.co.za");
Note that when you create a custom constructor, the compiler will not create the default, no-argument constructor. The default constructor will need to be explicitly created as follows :
public class Socket{
public Socket(String url) {
}
public Socket(){
}
}
And you can still either create socket objects by calling the default constructor or the custom constructor.
Socket socket = new Socket("http://chat.peruzal.co.za");
//or the default, no-agument constuctor
Socket socket = new Socket();