8.Constructor
Thursday, August 20, 2009
Initializing Objects with Constructors
In the previous post we have seen how to declare a method inside a class and how to use that method by the help of the object, in this module we are going to learn how to use a constructor to ensure that an object’s data is initialized when the object is created.
Access Modifiers
Modifiers are keywords that give additional meaning to code and classes. These are two types.
1.Access Modifiers
2.Non Access Modifiers
A class’s features such as class itself, its instance variables and its methods and constructors are accessible or are available to other classes depending upon which access modifier is used. Access modifiers are
1.public
2.private
3.protected
public access modifier
The features of a class are available to other classes .Public access modifier, as the name suggests, makes class features publicly available to a class. Hence any class in source code module has access to public parts of a class.
private access modifier
Private access modifier is the most restrictive access modifier. A private access modifier when used inside a class is accessible only in the class.
protected access modifier
Protected modifier can be used for variables, methods and inner classes. The class methods and fields that are declared as protected are available to classes that are subclasses. Use protected access modifier, when you want to restrict access to class features by unrelated classes.
Constructor
Constructor is a special method that does not have return type and has same name that of class name. Which means constructor can act as a normal method or function but it cannot return any value.
Then what is the use of constructor if it cannot return anything?
As mentioned in the previous post, when an object of class Student is created its instance variable sname is initialized to null by default. What if you want to provide a student name when you create a Student object? Each class you declare can provide a constructor that can be used to initialize an object that is created. In fact, Java requires a constructor call for every object that is created. Keyword new calls the class’s constructor to perform the initialization. The constructor call is indicated by the class name followed by parentheses.For example have a look at this program given below.
In the above class public Student() is a constructor for the class Student
In the Main class we need to create Student object to initialize the constructor.
The empty parentheses after new Student() indicate a call to the class’s constructor without arguments. By default the compiler provides a default constructor with no parameter in any class that does not explicitly include a constructor.
A constructor will have the fallowing characteristics.
1. A constructor can be used to initialize an object of a class when the object is created
2. Constructors can specify parameters.
3. A constructor does not have any return types.
4. A constructor can be overloaded
5. Constructor can be declared in public part of a program
6. A class can have more than one constructor
7. If no constructor is provided for a class, the compiler provides a default constructor with no parameters.
When you declare a class, you can provide your own constructor to specify custom initialization for objects of your class. For example , you might want to specify a student name for a Student object when the object is created, as in
For more details, have a look at the fallowing examples
Example 1
Example 2
Keyword “THIS”
Keyword “this” is associated with object. It is used to indicate current object and also to resolve the ambiguity between fields of class and parameters of a constructor. To understand more about “this” have a look at the fallowing example.
The above statement in the program
Indicates that variable sname of this object should assign value of a variable sname which is passed through the constructor.
In the previous post we have seen how to declare a method inside a class and how to use that method by the help of the object, in this module we are going to learn how to use a constructor to ensure that an object’s data is initialized when the object is created.
Access Modifiers
Modifiers are keywords that give additional meaning to code and classes. These are two types.
1.Access Modifiers
2.Non Access Modifiers
A class’s features such as class itself, its instance variables and its methods and constructors are accessible or are available to other classes depending upon which access modifier is used. Access modifiers are
1.public
2.private
3.protected
public access modifier
The features of a class are available to other classes .Public access modifier, as the name suggests, makes class features publicly available to a class. Hence any class in source code module has access to public parts of a class.
private access modifier
Private access modifier is the most restrictive access modifier. A private access modifier when used inside a class is accessible only in the class.
protected access modifier
Protected modifier can be used for variables, methods and inner classes. The class methods and fields that are declared as protected are available to classes that are subclasses. Use protected access modifier, when you want to restrict access to class features by unrelated classes.
Constructor
Constructor is a special method that does not have return type and has same name that of class name. Which means constructor can act as a normal method or function but it cannot return any value.
Then what is the use of constructor if it cannot return anything?
As mentioned in the previous post, when an object of class Student is created its instance variable sname is initialized to null by default. What if you want to provide a student name when you create a Student object? Each class you declare can provide a constructor that can be used to initialize an object that is created. In fact, Java requires a constructor call for every object that is created. Keyword new calls the class’s constructor to perform the initialization. The constructor call is indicated by the class name followed by parentheses.For example have a look at this program given below.
// Student.java
/**
*
* @author Sudarsan
*/
class Student {
//This is a constructor which is used to construct the Student Object
public Student()
{
System.out.println("Welcome to Student Class");
}
}
In the above class public Student() is a constructor for the class Student
// This is an Application which is used to run Student Class
/**
*
* @author Sudarsan
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Creation of the Object for Student Class
Student s=new Student();
}
}
In the Main class we need to create Student object to initialize the constructor.
The empty parentheses after new Student() indicate a call to the class’s constructor without arguments. By default the compiler provides a default constructor with no parameter in any class that does not explicitly include a constructor.
A constructor will have the fallowing characteristics.
1. A constructor can be used to initialize an object of a class when the object is created
2. Constructors can specify parameters.
3. A constructor does not have any return types.
4. A constructor can be overloaded
5. Constructor can be declared in public part of a program
6. A class can have more than one constructor
7. If no constructor is provided for a class, the compiler provides a default constructor with no parameters.
When you declare a class, you can provide your own constructor to specify custom initialization for objects of your class. For example , you might want to specify a student name for a Student object when the object is created, as in
Student s=new Student(“Welcome to Hrithik”);
For more details, have a look at the fallowing examples
Example 1
// Student class with a constructor to initilize the Student Name
/**
*
* @author Sudarsan
*/
public class Student {
private String sname;
//Constructor initializes sname with String passed as parameter
public Student(String name)
{
sname=name;
}
public void setSname(String name)
{
sname=name;
}
public String getSname()
{
return sname;
}
public void showMessage()
{
System.out.printf("Welcome to "+getSname());
}
}
// Main class for the Student Object
/**
*
* @author Sudarsan
*/
public class StudentTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Creation of Student Objects
Student s1=new Student("Hrithik");
Student s2=new Student("Kamal");
// display initial values for sname for each Student
System.out.println("Student Name is :"+s1.getSname());
System.out.println("Student Name is :"+s2.getSname());
}
}
Example 2
// Fruit.java
/**
*
* @author Sudarsan
*/
public class Fruit {
boolean seedLess;
boolean seasonal;
float price;
//This Constructor having three parameters boolean, boolean and float
public Fruit(boolean seed,boolean season,float p)
{
seedLess=seed;
seasonal=season;
price=p;
}
public void print()
{
System.out.println("Fallowing are the Properties of Fruit");
if(seedLess)
{
System.out.println("Fruit is seedless");
}
else
{
System.out.println("Fruit is seeded");
}
if(seasonal)
{
System.out.println("Fruit is Seasonal");
}
else
{
System.out.println("Fruit is not seasonal");
System.out.println("Price is "+price);
}
}
}
public class FruitDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//Constructing Fruit object by passing appropriate parameters
Fruit f=new Fruit(true,false,20.25F);
// Invoking print method of Fruit class
f.print();
}
}
Keyword “THIS”
Keyword “this” is associated with object. It is used to indicate current object and also to resolve the ambiguity between fields of class and parameters of a constructor. To understand more about “this” have a look at the fallowing example.
// Using this operator
/**
*
* @author Sudarsan
*/
public class Student {
private String sname;
public Student(String sname)
{
this.sname=sname;
}
public void print()
{
System.out.println("The Student Name is :"+sname);
}
}
The above statement in the program
this.sname=sname;
Indicates that variable sname of this object should assign value of a variable sname which is passed through the constructor.
// StudentTest.java
/**
*
* @author Sudarsan
*/
public class StudentTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Student s=new Student("Hrithik");
s.print();
}
}
Labels:
Constructors