Opening class in package from console in Java

前端 未结 2 1380
梦毁少年i
梦毁少年i 2020-12-20 10:09

So when i try to open a java class that\'s not in a package from the command prompt it all works fine, but when I try to open a class that\'s in a package it gives me NoClas

2条回答
  •  囚心锁ツ
    2020-12-20 10:47

    What I can infer is, you have two classes:

    Test.java:

    // no package defined here
    
    class Test{
        public static void main(String[] args){
            System.out.println("Test");
        }
    }
    

    so you can compile and run it using:

    javac Test.java
    java Test
    

    Another class:

    Test.java:

    package test; // package defined here
    
    class Test{
        public static void main(String[] args){
            System.out.println("Test");
        }
    }
    

    And thus doing same thing gives you error. For this you need to be in the parent directory of 'test' folder in your terminal or cmd and use:

    java test.Test
    

    No problem with compiler. You can compile as usual using javac Test.java from inside 'test' folder.

提交回复
热议问题