-
Notifications
You must be signed in to change notification settings - Fork 3
Chapter 2 : Classes, Objects and Methods
- Class contains variables (data members) and functions (member functions / methods).
- A class is a template for an object, and an object is an instance of a class.
- Class is a collection of objects of similar types.
- Class is a user defined data type.
- Syntax:
class ClassName {
datatype instance-variable1; datatype instance-variable2;
:
datatype instance-variableN;
return_datatype methodName1(parameter-list)
{
// body of method
}
return_datatype methodName2(parameter-list)
{
// body of method
}
:
return_datatype methodNameN(parameter-list)
{
// body of method
} }
Description of Syntax:
- Class is defined using class keyword. ClassName is any valid java identifiers.
- Data or variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another. The variables and functions defined inside the class are called members of the class.
- Class declaration only creates a template; it does not create an actual object.
- Class body written inside curly braces { and }. It does not terminate with semicolon.
import java.lang.*;
class Rectangle
{
int len, bre;
void getData(int l, int b)
{
len = l;
bre = b;
}
void putData()
{
System.out.print(“Area = “ + len*bre);
}
}
classRectArea
{
public static void main(String args[ ])
{
Rectangle r = new Rectangle();
r.getData(20,15);
r.putData();
}
}
// Output: Area = 300
-
Object is an instance of a class. Creating an object is called as instantiating an object.
-
An object is a block of memory that contains space to store instance variables and methods.
-
Once the class is defined we can create any number of objects of that class.
-
Objects are created by using new operator (dynamic memory allocation operator).
-
Steps for Creating Object: Creating objects of a class is a two-step process.
-
Step 1: Declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object.
-
Syntax: ClassName reference_variable;
-
Example: Rectangle r; // declare reference to object.
-
After this line executes r contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use object rat this point will result in a compile-time error.
-
Step 2: Acquire an actual, physical copy of the object and assign it to that variable. We can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is the address of memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.
-
Syntax: reference_variable = new ClassName();
-
Here, reference_variable is a variable (object) of the class type being created. The ClassName is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class.
-
Example: r = new Rectangle(); // allocate a Rectangle object
-
Above line allocates an actual object and assigns a reference of it to r. After this line executes, we can user as a Rectangle object. But in reality, r simply holds the memory address of the actual Rectangle object. The effect of these two steps of code is shown in Figure.
-
Above both statements can be combined into a single statement as follows:
-
ClassName object_name = new ClassName();
-
Rectangle r = new Rectangle();
-
Here Rectangle() is default constructor.
- One object reference can be assigned to another object reference variable, then the copy of the object is not created but copy of the reference is made.
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
- Here,r1 and r2 refer to same objects and no separate copy will be created. It simply makes r2 refer to the same object as r1.
- Thus, any changes made to the object through r2 will affect the object to which r1 is referring, since they are the same object.
- Although r1 and r2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to r1 will simply unhook r1 from the original object without affecting the object or affecting r2.
- For example:
Rectangle r1 = new Rectangle ();
Rectangle r2 = r1;
// ...
r1 = null;
Here, r1 has been set to null, but r2 still points to the original object.
- Classes consist of two things: instance variables and methods. Syntax:
return_type function_name (parameter_list)
{
// body of method
}
- Example:
void calculate(int l, int b)
{
len = l;
bre = b;
System.out.print(“Area = “ + len*bre);
}
- Here, return_type specifies the type of data returned by the method. This can be any valid type, including class type. If the method does not return a value, its return type must be void.
- Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value;
- The function_name of the method is any legal identifier other than those already used by other items within the current scope.
- The parameter_list is a sequence of type and identifier pairs separated by commas. If the method has no parameters, then the parameter list will be empty.
- Data or variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables.
- Thus, the data for one object is separate and unique from the data for another.
- Syntax : datatype instance-variable1, instance-variable2, instance-variableN;
- Example : int a, b, c;
- Object contains data members (instance variables) and member functions (methods). Each object has its own memory space for data members.
- Object name and dot (.) operator is used to access variables and methods from outside the class.
- Variables and methods can be access directly from within the class.
- Syntax: object_name . Variable_name = value;
- Object_name . method_name(parameter_list);
- Example: r1.len = 20; r2.len = 10; r1.bre = 15; r2.bre = 8; r1.calculate (20, 15); r2.calculate (10, 8);
- Array of object is the collection of objects of the same class.
- The given syntax will define an array of reference, therefore assign object to individual reference in the array to declare the array of object.
- Method 1: ClassName array_name[]; array_name = new ClassName[size];
- Method 2: ClassName array_name[ ] = new ClassName[size]; Here, array_name is the array of object.
- Example:
Student s[];
s = new Student[5];
Or
Student s[ ] = new Student[5];
- It will create array of 5 objects of student class.
- We need to use constructor in order to construct array of objects as follows:
for(int i=0;i<=4;i++)
{
s[i] = new Student();
}
// Program to accept & display data of five students.
import java.io.*;
class Student
{
String name;
int rollno;
float per;
InputStreamReaderisr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
void getData()
{
try
{
System.out.println("Input student details: ");
name=br.readLine();
rollno=Integer.parseInt(br.readLine());
per=Float.parseFloat(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception Occurred: “ + e);
}
}
void putData()
{
System.out.println("Name = " + name);
System.out.println("Roll No = " + rollno);
System.out.println("Percentage = " + per);
}
}
class Program1
{
public static void main(String args[])
{
Student s[] = new Student[5];
int i;
for(i=0;i<=4;i++)
s[i] = new Student();
for(i=0;i<=4;i++)
s[i].getData();
for(i=0;i<=4;i++)
s[i].putData();
}
}
- We have seen previously that, object can be initialize in two ways:
- Use dot operator to assign values to instance variables individually.
- Use member functions / methods to initialize the instance variables.
- But both of these approaches are tedious. Simple solution for the above problem is to use constructor.
- Constructor is special member function which initializes an object when it is created. It is known as automatic initialization of object.
- Constructor is called automatically whenever an object of its class is created.
- It is called constructor because it constructs the values of data members of the class.
- Constructor name is same as that of class name.
- Constructors are called automatically when objects are created.
- Constructor does not have return type, not even void, and they cannot return values.
- Constructor cannot be inherited, though a derived class can call the base class constructor.
- We cannot refer to their address.
- Constructors make implicit calls to new when memory allocation is required.
- They are invoked automatically when the objects are created, so programmers need not to worry about calling constructor.
- It initializes the objects at run time while declaring it. So exact required memory will be allocated.
- It brings Class closer to built-in data type.
No, it’s not mandatory to use constructor in a class. When constructor is declared for a class, initialization of class objects becomes compulsory.
- Types of Constructors: There are basically two types of constructors:
- Default Constructor
- Parameterized Constructor
- Implicit Constructor
- Explicit Constructor
- Constructor that accepts no parameters is called as default constructor.
class Sample
{
int m,n;
Sample() // Default Constructor
{
m=n=0;
}
};
- If no such a constructor is defined then the compiler supplies a default constructor.
- Here a statement: Sample sobj = new Sample( );invokes (call) the default constructor.
// Program to demonstrate default constructor.
class Rectangle
{
int len,bre;
void Rectangle()
{
len = 10;
bre = 8;
}
}
void display()
{
System.out.println(“Area = “ + len*bre);
}
class DefaultCon
{
public static void main(String args[ ])
{
Rectangle r = new Rectangle ( ); // call default constructor
r.display( );
}
}
// Area = 80
- Constructor that accepts parameters is called as parameterized constructor.
class sample
{
int m,n;
sample (int x, int y) // Parameterized Constructor
{
m=x;
n=y;
}
};
- While creating objects we must pass one or more parameters in order to invoke this constructor.
- Above constructor can be invoked (call) as: samplesiobj = new sample(10,20);
// Program to demonstrate parameterized constructor.
class Rectangle
{
int len,bre;
void Rectangle(int l, int b)
{
len= l;
bre = b;
}
void display()
{
System.out.println(“Area = “ + len*bre);
}
}
class ParaCon
{
public static void main(String args[ ])
{
Rectangle r = new Rectangle (20, 15); // call parameterized constructor
r.display( );
}
}
// Output: Area = 300
- If programmer does not write any constructor, JVM or the java tool may provide the default constructor automatically. Such a constructor which is not coded by programmer is called as implicit constructor.
- The constructor which is explicitly written by the programmer is called as explicit constructor.
- Using more than one constructor in a class with different parameter list is called as multiple constructors in a class or constructor overloading.
- Proper constructor will be invoked based on parameters pass at the time of object declaration.
// Program to demonstrate constructor overloading.
class Area
{
int len,bre;
Area()
{
len=12;
bre=8;
}
Area(int l)
{
len=bre=l;
}
Area(int l,int b)
{
len=l;
bre=b;
}
void display()
{
System.out.println("Area = " + len*bre);
}
}
class ConsOverload
{
public static void main(String args[])
{
Area a1=new Area();
a1.display();
Area a2=new Area(7);
a2.display();
Area a3=new Area(20,15);
a3.display();
}
}
// Output: Area = 96
// Area = 49
// Area = 300
- When instance method or constructor is called by an object, then this pointer is used to point the current object under reference.
- The members of the current object like instance variables, methods and constructors can be referred by using this pointer. Use of this with constructor:
- Keyword this can be used within a constructor to call another constructor or nested constructor.
- In following program, class contains a set of constructors. Each constructor initializes some or all of the Cube’s member variables. Constructors provide a default value for any member variable whose initial value is not provided by an argument.
- Compiler first determines which constructor to call, based on the number and type of arguments.
// Program to demonstrate use of this with constructor.
class Cube
{
int length, breadth, height ;
public int printVolume( )
{
System.out.println (“Volume = “ + length * breadth * height );
}
Cube()
{
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube(int l, int b)
{
this(l, b, 10);
System.out.println("Finished with Parametrized Constructor having 2 params");
}
Cube(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parametrized Constructor having 3 params");
}
public static void main(String[] args)
{
Cube cubeObj1, cubeObj2;
cubeObj1 = new Cube();
cubeObj2 = new Cube(10, 20, 30);
cubeObj1.printVolume();
cubeObj2.printVolume();
}
}
// Output: Finished with Parametrized Constructor having 3 params
// Finished with Parametrized Constructor having 2 params
// Finished with Default Constructor
// Finished with Parametrized Constructor having 3 params
// Volume = 1000
// Volume = 6000
- Using same function name more than once in a class having different parameter list is called as method overloading.
- The difference may either in the number or types of parameters.
- Proper method will be invoked based on arguments pass at the time of function call.
- Java supports polymorphism through method overloading – “one interface, multiple methods”.
- Method overloading is used when objects are required to perform similar tasks but using different input parameters.
// Program to demonstrate constructor overloading.
Class Area
{
int len,bre;
void getVal()
{
len=12;
bre=8;
}
void getVal(int l)
{
len=bre=l;
}
void getVal(int l,int b)
{
len=l;
bre=b;
}
void display()
{
System.out.println(“Area = “ + len*bre);
}
}
class ConsOverload
{
public static void main(String args[])
{
Area a1=new Area();
a1.getVal();
a1.display();
Area a2=new Area();
a2.getVal(7);
a2.display();
Area a3=new Area();
a3.getVal(20,15);
a3.display();
}
}
// Output: Area = 96
// Area = 49
// Area = 300
- We need to use object and dot operator to call method of the class.
- A method can be called inside the body of another method of the same class. In this there is no need to use object and dot operator to call the method. It is known as nesting of methods.
// Program to demonstrate nesting of methods.
class Nesting
{
int m,n;
Nesting(int x,int y)
{
m=x;
n=y;
}
int largest()
{
if(m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest(); // nesting of methods
System.out.println("Largest Value="+large);
}
}
class NestingTest
{
public static void main(String args[])
{
Nesting n=new Nesting(50,40);
n.display();
}
}
// Output: Largest Value = 50