D
D
d3coy_002019-10-03 16:45:09
Java
d3coy_00, 2019-10-03 16:45:09

Java method inheritance?

Hello, I came across this line:


The Thread class is responsible for working with threads in Java. To create a new thread to perform a task means to create an instance of the Thread class and associate it with the desired code. This can be done in two ways:
1) form a subclass from Thread;
2) implement the Runnable interface in your class, and then pass class instances to the Thread constructor.

Inheritance of all class methods through a subclass, respectively, is performed as follows:
public class PingPongThread extends Thread{
   PingPongThread(String name){
       this.setName(name); // переопределяем имя потока
   }

   @Override
   public void run() {
       Ball ball = Ball.getBall();
       while(ball.isInGame()){
           kickBall(ball);
       }
   }

   private void kickBall(Ball ball) {
       if(!ball.getSide().equals(getName())){
           ball.kick(getName());
       }
   }
}

Is it possible to call methods from the Thread class without inheriting the entire class in a self-written one? I understand this is the second option, how is it implemented? How about in Python? Performing a simple import and then in a self-written class call the necessary function, for example, like this? :
import socket

class test:
    def __init__(self):
        print("Объект создан")
        self.create_socket()

    def create_socket(self):
        HOST = "127.0.0.1"
        PORT = "9999"
        PORT = int(PORT)

        # supports the context manager type
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.bind((HOST, PORT))  # associate the socket with a specific network interface
            print("socket created")


def main():
    t_obj = test()

if __name__ == '__main__':
    main()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Alexandrov, 2019-10-03
@d3coy_00

Thread myThread = new Thread() {
    public void run() {
       //тут код ваш
    }  
};

Or like this with lambdas
Thread myThread  = new Thread(() -> {
    //тут код ваш
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question