官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 文山县| 永康市| 准格尔旗| 正蓝旗| 龙南县| 罗山县| 梅河口市| 河西区| 娱乐| 张掖市| 萨嘎县| 蓬莱市| 张家港市| 介休市| 荥经县| 霍林郭勒市| 喀喇沁旗| 彭泽县| 商南县| 江西省| 新津县| 林芝县| 桑植县| 三穗县| 丽江市| 京山县| 淳化县| 芷江| 阿拉善右旗| 聊城市| 临西县| 和静县| 宁化县| 石家庄市| 外汇| 柘荣县| 卓尼县| 康马县| 鹿泉市| 东明县| 明光市|