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

Accessing a method in a different class

Let's say we face a situation where we are working with one class and we need to access an object in another class; this can be done in Java. Let's use an example to help explain this. Let's use two classes, Firstclass() (from the Accessing an object in Java section ), and we'll create a new class, called secondclass(). On creating a new class, the default code is created by the editor and we're able to add code in it. We add a random method, public void setData(), within which we print the I am in second class method statement.

Now, we want the setData() method in the Firstclass() class. Basically we want to execute the setData() method in Firstclass(). And methods can be called only with the objects of that particular class. To do so, we create an object in the method that calls the method in the other class. We use similar code to what we used in the previous example to allocate memory for an object. The following code is added in the main method of Firstclass():

secondclass sn= new secondclass();
sn.setData();

While typing the code in the main class, when we type sn. to call the method, we will again get all the choices of methods that there are in Java. Since we want to call setData(), we select it from the multiple options that are shared with us. This will successfully bring setData() into in the main method of Firstclass() by creating an object for the class.

If we run the code, we will get the following output:

Output displaying I am in second class method as per the code
主站蜘蛛池模板: 安阳县| 商丘市| 遵化市| 筠连县| 清原| 页游| 弥渡县| 罗江县| 二手房| 广州市| 仙居县| 佳木斯市| 砀山县| 广河县| 方城县| 顺义区| 成武县| 鹤壁市| 喀什市| 靖江市| 礼泉县| 漳平市| 志丹县| 苍南县| 连州市| 黄陵县| 府谷县| 崇文区| 铁岭市| 集安市| 崇明县| 枣庄市| 化德县| 宁安市| 岱山县| 舞阳县| 丹江口市| 永顺县| 南康市| 浦城县| 交口县|