Accessing an object in Java

To access the method of the class, we write the object name and then . (dot). All the methods that qualify for the class are displayed in a drop-down—this is another great feature in Eclipse. We can just look for the method in the drop-down rather than searching for it through the code.

In the example, we are using the getData() method. The rest of the methods shown are all built-in Java methods. Observe how the methods are displayed:

Drop-down showing all the class methods available to the editor to use

On clicking on getData(), the getData() block will be transferred to the line where the object was called, and when we run the program, the code will be executed as it is part of the main block. The accessing code will finally look like this:

fn.getData();

Let's see what the final code for this example will look like:

package coreJavaTraining;

public class Firstclass {

public void getData()
{
System.out.println(" I am in method")
}
public static void main(String[] args)
{
Firstclass fn=new Firstclass();
fn.getData();
System.out.println("hi");
System.out.println("hello world");
}
}

So if we run the class given in the example, our result will be as follows:

Output displaying I am in method as per the code

I am in method is what we see in the output; this is because control starts from the memory-allocation line, creates an object, and using the object we call the method of that class. Control goes back to the getData() block and completes the lines of code that are present in that particular block; it executes the print statement, and we see that it gets printed. This is why objects are powerful in calling a method.

The same technique can be used for calling integers. Let's say we declare a variable in the a class and assign a value to it. We can print the variable value by adding the following line in the main method:

System.out.println(fn.a);

This is one way of using classes, objects, and methods in Java; basically we are encapsulating.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.198.146