开发者

Java: Call subclass out of another subclass

开发者 https://www.devze.com 2023-03-29 17:16 出处:网络
How can I call a subclass out of another subclass, if the first class was initialized in the main class? It\'s something like that:

How can I call a subclass out of another subclass, if the first class was initialized in the main class? It's something like that:

public class main {
    Sub1 test = new Sub1();
    Sub2 test2 = new Sub2();
    Sub2.bummer2();
}

Subclass 1:

public class Sub1 {
    public static void bummer() {
        System.out.println("got c开发者_运维百科alled");
    }
}

The other subclass:

public class Sub2 {
    public static void bummer2() {
        //here i want to execute Sub1.bummer() without having to initialise it first
    }
} 

How can I do that?


Just call Sub1.bummer(). There's no need to create any instances to call static methods. This can be called from any class, given that it's a public static method.


Neither of those are subclasses, but you can just call Sub1.bummer(), as bummer() is public static. I don't know what you mean when you say you don't want to initialize it first.


If you intended the bummer functions to be static, then everyone's answers above are correct. If, however, you intended the functions to be instance methods, then perhaps the decorator pattern will get you what you need

E.g.

abstract class Mybase
{
abstract void bummer();
}

class Sub1 extends Mybase
{
public Sub1() {

}
void bummer() {System.out.println(" sub1 is bummed ");};
}

class Sub2 extends Mybase
{
Mybase b;
public Sub2(Mybase b) {
    this.b = b;
}

void bummer() {b.bummer(); System.out.println(" sub2 is bummed ");}

}

class Sub3 extends Mybase
{
Mybase b;
public Sub3(Mybase b) {
    this.b = b;
}

void bummer() {b.bummer(); System.out.println(" sub3 is bummed ");}

}

Then executing

Mybase m1 = new Sub3(new Sub2(new Sub1()));
m1.bummer();

Outputs

sub1 is bummed 
sub2 is bummed 
sub3 is bummed 


Since it's public and static, in Sub2 you can just call

Sub1.bummer();


Static methods are attached to the class, not an instance of the class, so you never needed to create test1 or test2 unless there are some sneaky side-effects that you have omitted. This is all you need:

public class Sub2 {
    public static void bummer2() {
        Sub1.bummer();
    }
}

That's it.

0

精彩评论

暂无评论...
验证码 换一张
取 消