简体   繁体   中英

calling methods from different package JAVA

I have two packages; pack1 and pack2. in pack1 I have two classes the main called Prog and another one called ClassA. In pack2 I have one class called ClassB.

I am trying to understand why I can't call a method from ClassB using the object. I can do that using the main class but not with another class.

Here's the code:

package pack1;
import pack2.ClassB;

public class Prog {
    public static void main(String[] args){

    }
}

Code for ClassA

package pack1;
import pack2.ClassB;

public class ClassA {
    ClassB o3 = new ClassB();
    // Error won't compile
    System.out.println(o3.getText());

}

Code for ClassB:

package pack2;

public class ClassB {
    final String TEXT = "This is a text";

    public String getText(){
        return TEXT;
    }
}

The problem here isn't that you can't access the method. The problem is that statements must be enclosed either in a constructor, amethod-declaration or an initializer-block. So this would be valid code for example:

enter codepackage pack1;
import pack2.ClassB;

public class ClassA {
    ClassB o3 = new ClassB();

    public void someMethod(){
        System.out.println(o3.getText());
    }
}

//pack1 code here

package pack1;

import pack2.ClassB;

class ClassA {

}

public class Prog {

public static void main(String[] args) {
// write your code here
    ClassB o3 = new ClassB();
    // Error won't compile
    System.out.println(o3.getText());


}

}

//pack2 code here

package pack2;

public class ClassB { final String TEXT = "This is a text";

public String getText() {
    return TEXT;
}

}[You don't need to create classA you can directly import pack2 and its class,method]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM