Calling a methods of object

Calling a methods of object


Posted in : Core Java Posted on : October 4, 2010 at 6:37 PM Comments : [ 0 ]

In this section, you will learn about calling a methods of object.

Calling a methods of object

Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows :

/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */
ObjectReference.MethodName();

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

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics