Почему методы из BaseTestClass можно вызвать без экземпляра класса?

Здравствуйте:
Имеем базовый тестовый класс:

public class BaseTestClass {

  private WebDriver webDriver;
  private String mainPage = "http://yandex.ru";

  @BeforeClass
  public void startBrowser() {
    //webDriver = new FirefoxDriver();
    webDriver = new ChromeDriver();
    webDriver.manage().window().maximize();
    webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    webDriver.get(mainPage);
  }

  @AfterClass
  public void stopBrowser() {
    webDriver.quit();
  }
  
  public void helloWorld(){
    System.out.println("Hello World");
  }
}

Почему в тесте можно вызвать методы и как статичные, и из объекта? Не могу этого понять… Это фишка тестового фреймворка? Использую TestNG

public class ViewUsefulLinksTest extends BaseTestClass{

    BaseTestClass bt = new BaseTestClass();

    @Test
    public void testViewUsefulLinks(){

        super.helloWorld();
        helloWorld();
        bt.helloWorld();
    }

}

Это “фишка” ООП, а именно - концепция наследования.

1 лайк

Я не понимаю, почему НЕстатичные методы вызываются как статичные и работают?
Их можно вызвать и в экземпляре класса и без объекта.
Не совсем понимаю конкретно этот момент, почему так?
Должна же быть ошибка, если метод НЕ статик, а я его пытаюсь без объекта вызвать…

Ясно. Видимо, намек прошел мимо. Тогда внимательно читаем раздел Inheritance:

What You Can Do in a Subclass

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
2 лайка

Потому что

Inheritance in Java provides a mechanism for the users to reuse the existing code within the new applications. It does this by allowing the programmer to build a relationship between a new class and existing class and define a new code in terms of existing code.