Why am I able to access a method without object in java

by Lokesh Sanapalli   Last Updated July 12, 2019 14:26 PM - source

Here's my code:

public class MyProjectPage extends AbstractPage {
    public boolean addDefaultProjectBymyProjects(String softwareName, String projectName,) {
        navigateTomyProjects();
    } 

    public void navigateTomyProjects() {
        clickElement(By.xpath(properties.getProperty("x.Myprojects.Icon")), "MyProjects");
    }
}

I am able to access method navigateTomyProjects() without an object; how is this possible?

Note: clickElement is a generic method in abstract page

Tags : java methods


Answers 2


navigateTomyProjects() is an instance method.
It is being called from addDefaultProjectBymyProjects(), another instance method.

These methods are not being accessed without an object; they are being accessed by this - the current instance against which these methods will be executed.

There is nothing mysterious about this code.

Bohemian
Bohemian
January 30, 2016 14:34 PM

Both the methods navigateTomyProjects() and addDefaultProjectBymyProjects() reside as instance methods in the same class. As a result, either of the methods can access the other method without explicitly creating an object of the class.

To be more precise, addDefaultProjectBymyProjects() calls navigateTomyProjects() internally as this.navigateTomyProjects(). Here, the this keyword refers to the current object (invoking object).

Pratanu Mandal
Pratanu Mandal
January 30, 2016 14:41 PM

Related Questions




Is it possible to overload Python assignment?

Updated September 21, 2018 07:26 AM