-3

I am just learning about OOP in Java, and I'm kinda running into a bug. I want to import a package onto another file. I want to import everything from the package, but it tells me to declare it public which makes sense but if I declare it public then it wants be to re-name the entire file. is there a way around this? Like if I have a few different classes in one package how would I create the objects on the other file?

enter image description here

enter image description here

I tried re-naming the file name and made it the same as the class.

Squash101
  • 1
  • 2
  • 2
    Providing CODE instead of images of it helps to get much faster recommendations from the community.it is one of the reasons that you get Downvote – eng Aug 05 '23 at 06:01
  • 4
    Please read: [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Turing85 Aug 05 '23 at 06:03
  • You could try (I would be curious to know)..... Put in the same folder a new file in with the correct name and same name class as the new file.java and public, and it should be extended from the class you do not want to change(has main method in it). – Samuel Marchant Aug 05 '23 at 06:28
  • One file can contain at most one public, top-level class. So the answer is: put your classes in their own files. – Sweeper Aug 05 '23 at 06:32
  • Just want to say: don't get discouraged by the downvotes, this is actually a nice place if you follow all the (un)written rules. – HolyBlackCat Aug 23 '23 at 04:41

1 Answers1

0

Answer 1: Importing package has nothing to do with how many main methods you have. main method under public class will be executed by default.

Answer 2: Your java file must have same name as your public class. See this stackoverflow answer to the question Can a java file have more than one class?:

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.

Basically you can declare public static void main(String[] args) inside that public class. Which you did in class OOP3.

Answer 3: If you have different classes in a package you can use them like this:

import packagename.ClassA;
import packagename.ClassB;

public class OOP {
    
    public static void main(String[] args) {
        ClassA objA = new ClassA();
        ClassB objB = new ClassB();
        objA.doSomething();
        // etc.
    }

}