Declaring Objects
Obtaining objects of a class is a two-step process. First, you must
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. Second, you must acquire an actual, physical copy of the object
and assign it to that variable. You 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.
First Method:
Box mybox = new Box();
Second Method:
Box mybox; // declare reference to object mybox = new Box(); // allocate
a Box object
The first line declares mybox
as a reference to an object of type Box.
After this line executes, mybox
contains the value null, which
indicates that it does not yet point to an actual object. Any attempt to use mybox at this point will result in a
compile-time error. The next line allocates an actual object and assigns a
reference to it to mybox. After the
second line executes, you can use mybox
as if it were a Box object. But in
reality, mybox simply holds the
memory address of the actual Box
object.
Constructor:
A constructor initializes an
object immediately upon creation. It has the same name as the class in which it
resides and is syntactically similar to a method. Once defined, the constructor
is automatically called immediately after the object is created, before the new operator completes. Constructors
look a little strange because they have no return type, not even void. This is because the implicit
return type of a class’ constructor is the class type itself.
Example for Constructor:
class rect{
int Ilength,Ibreadth;
// Here
rect() is an Constructor rect(){
// here the member variables are initialized Ilength=10;
Ibreadth=20;
}
int fun_area()
{
return Ilength*Ibreadth;
}
}
public class cons {
public static void main(String args[])
{
rect op=new rect();
int Iarea;
Iarea=op.fun_area();
System.out.println("Area
of rectangle is" + Iarea);
}
}
Parameterized
Constructors:
We can pass the initialization
values to the constructor.it is know as parameterized constructor.
import java.util.Scanner;
class cube{
int ISide; cube(int x){
// this is constructor ISide=x;
}
int fun_volume()
{
return ISide*ISide*ISide;
}
}
public class paramconst {
public static void main(String args[])
{
Scanner sr= new
Scanner(System.in); System.out.println("Enter
the side value"); int side=sr.nextInt();
// Parameterised Constructor cube op=new cube(side);
int IVolume; IVolume=op.fun_volume();
System.out.println("Volume of Cube is" + IVolume );
}
}
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.