What happens when I define an abstract class and not a declaration.

public class Temp {
public static void main(String args[]) {
    A ref;
    B objB = new B();
    C objC = new C();
    ref = objB;
    ref.show();
    ref = objC;
    ref.show();

}

}

abstract class A {

abstract void show();

 {
    System.out.println("In Class A");
 }
}

class B extends A {

void show() {
    System.out.println("In class B");
   }
 } 
class C extends B {

void show() {
    System.out.println("In Class C");
 }
}

      

In the above abstract methods of code containing a method definition. But the books indicate that an abstract method should only contain a declaration, and the definition of that method. When I run this program, it outputs the following output without any error. Please explain to me how the result shows below.

In Class A
In Class A
In class B
In Class C

      

+3


source to share


2 answers


Your abstract class does not contain a method definition. Your abstract class contains an abstract method and an initializer block.

abstract class A {
    // Abstract method
    abstract void show();

    // Initializer block, completely unrelated to show
    {
        System.out.println("In Class A");
    }
}

      

Initializer blocks are run when an object is constructed - similar to constructors (but you can have several, and they cannot have arguments). This is exactly the same as if you wrote:



abstract class A {
    // Abstract method
    abstract void show();

    // Constructor
    public A()
    {
        System.out.println("In Class A");
    }
}

      

The exit is carried out from:

A ref;
B objB = new B(); // calls B constructor, then A constructor which prints "In Class A"
C objC = new C(); // calls C constructor, then A constructor which prints "In Class A"
ref = objB;
ref.show(); // prints "In Class B"
ref = objC;
ref.show(); // prints "In Class C"

      

+8


source


This abstact method has no implementation in class A:

abstract void show();

      

A semicolon ends a method declaration without an implementation.

The next block is an instance initialization block (which runs when the isntance class is created, before the constructor code is executed), not associated with an abstract method:

{
    System.out.println("In Class A");
}

      



If you tried to give an implementation to an abstract method, it looks like this and won't compile:

abstract void show()
{
    System.out.println("In Class A");
}

      

As for the result obtained:

In Class A // new B() causes the instance initialziation block of A to be executed before the (default) constructor of A 
In Class A // new C() causes the instance initialziation block of A to be executed before the (default) constructor of A 
In class B // first ref.show() executes B show, since you assigned objB to ref
In Class C // second ref.show() executes C show, since you assigned objC to ref

      

+4


source







All Articles