一、编译单独一个java程序
Hello.java
public class Hello{ public static void main(String args[]){ System.out.PRintln("Hello World!"); }}xl@Ubuntu:~/java$ javac Hello.java //在当前目录下产生Hello.class文件
xl@ubuntu:~/java$ lsHello.class Hello.javaxl@ubuntu:~/java$ java Hello // 执行Hello.classHello World!
二、编译一个带包的java程序Hello.java
package hello.world;public class Hello{ public static void main(String args[]){ System.out.println("Hello World!"); }}xl@ubuntu:~/java$ javac Hello.java // 在当前目录下产生Hello.class文件xl@ubuntu:~/java$ lsHello.class Hello.java
xl@ubuntu:~/java$ java Hello // 在执行的时候显示找不到Hello这个类,原因是因为程序中包含包hello.world,执行类的时候回去按照这个包的路径来找。因此我们用下面的命令来执行。Error: Could not find or load main class Helloxl@ubuntu:~/java$ javac -d . Hello.java // 参数-d 指定生成class文件的位置xl@ubuntu:~/java$ ls // 此时我们看到在当前目录下生成了一个目录hello/world/ hello Hello.javaxl@ubuntu:~/java$ tree hello/ hello/└── world └── Hello.class1 directory, 1 file
xl@ubuntu:~/java$ java hello.world.Hello // 执行类的时候需要带上路径Hello World!
三、同一个包下,一个类调用另一个类
Lance.java
package hello.world;public class Lance{ public String getName(){ return "my name is lance"; }}Introduce.javapackage hello.world;import hello.world.Lance;public class Introduce{ public static void main(String args[]){ Lance name = new Lance(); System.out.println("hello world! " + name.getName()); }}xl@ubuntu:~/java$ javac -d . Lance.java // 参数-d . 表示在当前目录下产生hello/world/目录。并且生成Lance.classxl@ubuntu:~/java$ javac -cp . -d . Introduce.java // 参数-cp . 表示按照hello.world.Lance的路径寻找类,并且编译Introduce.java。此时在当前目录下产生hello/world/目录,并且生成Introduce.classxl@ubuntu:~/java$ tree hello/hello/└── world ├── Introduce.class └── Lance.class
1 directory, 2 filesxl@ubuntu:~/java$ java hello.world.Introduce hello world! my name is lance
四、一个包下的类调用另一个包下的类
Lance.java
package hello.world01;public class Lance{ public String getName(){ return "my name is lance"; }}Introduce.javapackage hello.world02;import hello.world01.Lance;public class Introduce{ public static void main(String args[]){ Lance name = new Lance(); System.out.println("hello world! " + name.getName()); }}xl@ubuntu:~/java$ javac -d . Lance.java // 参数-d . 表示在当前目录下产生hello/world01/目录。并且生成Lance.classxl@ubuntu:~/java$ javac -cp . -d . Introduce.java // 参数-cp . 表示按照hello.world01.Lance的路径寻找类,并且编译Introduce.java。此时在当前目录下产生hello/world02/目录,并且生成Introduce.classxl@ubuntu:~/java$ tree hello/hello/├── world01│ └── Lance.class└── world02 └── Introduce.class2 directories, 2 filesxl@ubuntu:~/java$ java hello.world02.Introduce // 执行Introduce类的时候需要指定路径hello world! my name is lance参考
http://blog.csdn.net/wen294299195/article/details/39964971
新闻热点
疑难解答