I am curious about how to use method of an extended class. For example

public class ConnectThread extends Thread {

public ConnectThread(BluetoothDevice device) {}
public void run() {}
public void write() {}
}

Then

Thread myThread = new ConnectThread(device);
myThread.run(); 

works because there is a method called run() in the parent class Thread. However I can't do

myThread.write() 

because write() is not a part of Thread class. How do I use write()? Thanks!

有帮助吗?

解决方案

((ConnectThread)myThread).write();

其他提示

myThread.write() doesn't work because it is only defined in child class and your object is of parent class.

So generally when you use polymorphism, all methods are defined in parent class and implementation can change across child classes. This was you are able to change implementation by writing different child classes but your code doesn't change if you use parent class object.

So for example :

I have a class Shape with method area in it:

Class Shape { public void area() { }};

Class Circle extends Shape {public void area { }};

Class DrawShapes { public void draw (Shape a) { a.draw()}};

Now in above setup you can go on implementing new shapes by extending Shape class but your DrawShapes stays intact.

You can just typecast the parent object reference to child class like

((ConnectThread)myThread).write()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top