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

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
主站蜘蛛池模板: 灵寿县| 巴马| 陆良县| 富民县| 托里县| 年辖:市辖区| 叶城县| 阿拉善右旗| 含山县| 水城县| 宁波市| 班戈县| 澜沧| 长葛市| 云安县| 明星| 德清县| 龙井市| 漯河市| 合肥市| 泰兴市| 鸡东县| 花莲市| 麦盖提县| 龙胜| 铜鼓县| 邹平县| 仙居县| 封开县| 合作市| 长海县| 烟台市| 湖北省| 皮山县| 乾安县| 平泉县| 萍乡市| 武陟县| 龙泉市| 岐山县| 红原县|