As i know whenever we want to call any method then we create object and invoke its method using obj.methodname
.
But below program calls the method of E
class without creating object. How this is possible? Please anyone help me to understand this concept.
I mean 'From below code, how this is possible to write E.test2();
? , i think it should be E obj=new E(); obj.test2();
E obj=new E(); obj.test2();
class E
{
int i;
static int j;
void test1()
{
System.out.println("From test1");
}
static void test2()
{
System.out.println("From test2");
}
}
class F extends E
{
int m;
static int n;
void test3()
{
System.out.println("From test3");
}
static void test4()
{
System.out.println("From test4");
}
}
public class G {
public static void main(String args[])
{
E.test2();
F.test2();
}
}
The method E.test2
is declared as static
which means that you can use this method without create an instance of that class. There are so many classes in Java that uses it.
See the docs:
static methods can be called using class name and do not require an object of that class.
Please read this: http://introcs.cs.princeton.edu/java/21function/
test2 method is static in class E , and static method are class specific not object specific ,and they are accessed using "classname.methodname" syntax. where methodname is static method of "classname"
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.