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

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
主站蜘蛛池模板: 思南县| 茂名市| 汪清县| 维西| 舞钢市| 靖远县| 荣成市| 天水市| 锦州市| 旌德县| 元谋县| 台湾省| 九江市| 勐海县| 韩城市| 文安县| 宁波市| 六安市| 望江县| 余姚市| 泊头市| 安国市| 天津市| 酉阳| 景宁| 霍城县| 内江市| 应用必备| 丰宁| 麻栗坡县| 彭山县| 内黄县| 宜川县| 桂阳县| 磴口县| 贞丰县| 南昌市| 陆川县| 大丰市| 册亨县| 布尔津县|