Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why abstract property is lost in a subclass of Runnable interface?

I am actually learning Threads. But get stuck with a very basic problem. I know if I inherit an interface in my class I have to give definitions of all the methods (mentioned in that interface) in my inherited class, else it has to be declared as abstract. Now I have tried very simple code...

import java.util.*;
import java.lang.*;
import java.io.*;


abstract class Code implements Runnable 
{
    public static void main (String[] args) throws java.lang.Exception
    {

    }
}

there was no problem in the compilation,and then I removed the abstract keyword from class code and it was showing me compilation error,saying class code is not abstract...

There has to be error. But then I did what ,checking some variation,extended Thread class also from class and recompiled the code. And I got no compilation error! Though I have not given the definition of run() method, neither I mentioned my class as abstract. there...

 class Code extends Thread implements Runnable 
{
    public static void main (String[] args) throws java.lang.Exception
    {

    }
}

means this class lost the abstract property. How was that possible? Anyone explain please.


1 Answers

Runnable is an interface which requires any class that implements it to implement a run() method

public class A implements Runnable {
    public void run() {
        // implementation of run
    }
}

Thread is a concrete class that implements the Runnable interface. That means it has concretely implemented the run() method.

public class Thread implements Runnable {
    public void run() {
        // Java's implementation of run
        // for the Thread class
    }
}

When you define a class that extends Thread it means that it will be extending the Thread class which has already implemented everything required for the Runnable interface. So you don't need to implement the run() method. You can however override the implementation from Thread and optionally call it if you need to.

class A extends Thread {
    @Override
    public void run() {
        // implementation of run
        // optionally call super.run();
    }
}
like image 90
Saeed Jahed Avatar answered Dec 07 '25 16:12

Saeed Jahed