I am not sure if the title is accurate. I have several classes like Tv and I want to use all of them in only one class. Is it possible to call the methods in Tv in another class? If so, do I need to revise the constructor in class Tv? (TS is an interface).
class Tv implements TS{
private String v;
public Tv(String v){
this.v = v;
}
public void open(){
System.out.println("open");
}
public void volume(String v){
...
}
}
public class TvSet{
public static void main(String args[]){
Tv t = new Tv("+");
}
}
I have tried this:
public class RunTv {
Remote r = new Remote("+");
Tv t = new Tv("+");
t.open();
}
The IDE reminds me “identifier expected after this token.” Should I modify Tv or RunTv?
The first problem is already answered by Owl and Roddy of the Frozen Pea, but to summarize: Yes you can call methods in another class as long as they are public and you have an instance of the class containing the method.
For your other problem with the “
identifier expected...” error, you should changeRunTv.You cannot call
t.open()outside a method block. If you changed it to something like this:Then whenever you call the
openNewTvmethod it will create a new instance ofRemoteandTvand it will then call theopenmethod in theTvinstance. To callopenNewTvyou could create an instance ofRunTvin yourmainmethod like this:If you do not want to create a new instance every time you have to open a new
Tvyou could make the method static, which means it will not belong any instance, but rather the class itself (To understand these things better, you should read this)You can make the method static like this:
Now you can call
openNewTvwithout having to create an instance ofRunTvlike this:Hope this helps. 🙂