This section contains the detail about creating object of the class.
Creating object of the class
An object is the instance of the class. In java 'new' keyword is used to create new object.
Steps to create a object :
Object Declaration :
An object is declared using a variable name(object name) and type of the objects.
Mainclass mc;
Object Instantiation :
The 'new ' key word is used to create the object.
mc = new Mainclass();
Object Initialization (Optional step):
The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
mc = new Mainclass("Ankit");
Example :
Given below complete example with output snap :
Mainclass.java
public class Mainclass { int myage; public Mainclass(String name) { // This constructor has one parameter, name. System.out.println("Name :" + name); } void setAge(int age) { myage = age; } int getAge() { System.out.println("Age :" + myage); return myage; } public static void main(String[] args) { /* Object creation */ Mainclass mc = new Mainclass("Ankit"); /* Call class method to set age */ mc.setAge(24); /* Call another class method to get age */ mc.getAge(); /* You can access instance variable as follows as well */ System.out.println("Fetched Value via object :" + mc.myage); } }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac
Mainclass.java C:\Program Files\Java\jdk1.6.0_18\bin>java Mainclass Name :Ankit Age :24 Fetched Value via object :24 |
[ 0 ] Comments