Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

The question is in Java,   ? for example

abstract class foo {

    abstract void bar( ); // <-- this is ok

    abstract static void bar2(); //<-- this isn't why?

}

1 Answer

0 votes
by (46k points)

I'll first mention some facts,

1. An abstract method is the one which is not performed in a particular class and so it must be performed by the child class.

2. Now, if there is an abstract method then the class need be abstract

3. We can't instantiate an abstract class. we need to subclass it to a particular class

4. Static methods can be obtained by a class name without generating an instance of the class

5. Static methods can't be reversed; they can only be shadowed

Acknowledging these facts, if we want to declare an abstract static method in a class then what happens?

1. That method won't have a sense as its abstract

2. As it is static it needs to be available via just the class name

Here there is an obstacle in our case. Why? 

This is because we can't request a method that produces no implementation. Right? And the compiler grasps that there is no possible subclass of the abstract class that force has implemented that method because the method is static and fact 5 from the above list restraints that static method can't be revoked. Here, JVM always requests a method from the reference type declaration rather than runtime type.

So, compiler delivers us the error if we try to declare an abstract static method.

Okay try this,

abstract class Parent {

static void print1() {

System.out.println("Parent.print1()");

}

abstract void print2();

}

class Child extends Parent {

static void print1() {

System.out.println("Child.print1()");

}

void print2() {

System.out.println("Child.print2()");

}

public static void main(String[] args) {

Parent p = new Child();

p.print1();

Child c = new Child();

c.print1();

}

}

The output is,

Parent.print1()

Child.print1()

As we see here also if the 'p' is of type Child() it summoned method of Parent because print1() is static and 'p' is of ref type Parent in the statement. Now, if we make print1() abstract in Parent then what appears to the above program? It won't work. right? because it will try to summon print1() in Parent class which is not defined.

Hope I am able to help a little.

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer

Browse Categories

...