简体   繁体   中英

Java- In inheritance, method can be invoked without creating a class

I have parent and child classes in which the parent class has a method- getData . I can call this method directly from the child class with or without creating an object. I am wondering how does the method become available in child class without creating an object. (It is not static method either) It was my understanding that we have to create an object to access the methods. Can anyone please explain why?

 public class testbase {

    public void getData(String Data) throws IOException{
        Properties prop1;

        prop1= new Properties();
        FileInputStream f= new FileInputStream("C:\\file.properties");
        prop1.load(f);


        String data= prop1.getProperty(Data);
        System.out.println(data);
    }

}


class testproperties_file extends testbase {

    @Test
    public void test_class() throws IOException{
        getData("name");

    }
}

As per

https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

A subclass inherits all the members (fields, methods , and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

I would suggest you to read more abour inheritance

Sub child inherits all the member methods from its super class.

If execution control reaches any non static method , it implies there is an object created and upon it that method is being invoked. this is the implicit reference to the currently executing object upon which any method is invoked. As the object of derived class has the behaviour of super class, then more behaviours gets added as per the defination of actual derived class and also if any behaviour is overriden then the behaviour derieved from super class gets modified.

I am wondering how can the method gets available in child class without creating an object.

class testproperties_file extends testbase {
    @Test
    public void test_class() throws IOException{
       getData("name");

    }
}

Here test_class() is an instance method. It means that all code invoked in this method may invoked methods available for an instance of the current class (here testproperties_file ). So, you are already in a object when this method is executing.

A instance of testproperties_file inherits from the testbase class.
It means that all public and protected instance methods of testbase may be invoked here. The public getData() instance method of testbase is so callable.


As a side note you should use uppercase and camelcase to name your class. TestBase and TestPropertiesFile are better as they follow the java coding convention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM