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
..................Content has been hidden....................

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