2

Why do I have access to the getName() method? My class doesn't extends the class Thread just implements the interface Runnable.

public class MyThread implements Runnable { public void run() { System.out.println("MyThread is running"); } public static void main(String[] args){ MyThread thread1 = new MyThread(); Thread thr = new Thread(thread1, "thread"); thr.start(); System.out.println(thr.currentThread().getName()); System.out.println(thr.getName());//Why do I have access to this method? } } 

2 Answers 2

6

You're not calling getName() on an instance of the MyThread class, you're calling it on an instance of the Thread class. You should consider renaming your class to MyRunnable because MyThread would seem like your class is some sort of Thread class, while it isn't.

Sign up to request clarification or add additional context in comments.

Comments

0

Every action you perform is in a thread. In case you are doing some action, in the main method while starting the program, it happens in the main thread.

The method currentThread is static, and it provides the thread that is currently executing that line and when you perform, getName() it is on that Thread object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.