UCB CS61b——Class 1

编译

在terminal中,运行Java程序,首先dir(相当于Linux中的ls)和cd到对应文件夹
javac xxx.java编译Java程序

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>javac hello_world.java

用window中的type命令查看编译出的class文件(不同于Linux中的cat)

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>type hello_world.class
漱壕   8 
         
      ()V Code LineNumberTable main ([Ljava/lang/String;)V
SourceFile hello_world.java     Hello world Phoebe

然后运行报错

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>java hello_world
错误: 找不到或无法加载主类 hello_world
原因: java.lang.NoClassDefFoundError: hello_pkg/hello_world (wrong name: hello_world)

再来看看hello_world.java的内容

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>type hello_world.java
package hello_pkg;

public class hello_world {
    public static void main(String[] args){
        System.out.println("Hello world Phoebe");
    }
}

去掉程序中的package hello_pkg,再次编译运行,就可以正常运行

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>javac hello_world.java

C:\Users\phoeb\IdeaProjects\beginner\src\hello_pkg>java hello_world
Hello world Phoebe

标准化执行Java程序有两步:
1、编译.java程序得到.class文件
2、interpret .class文件得到程序结果
为什么要得到.class文件?
1、.class文件已经经过类型检查,执行safer
2、对于机器来说,.class文件更加易于执行,会更快
3、保护知识产权

定义和实例化

Dog.java

package hello_pkg;

public class Dog {
    /*instance variables, you can have as many of these as
    * you want.*/
    public int weightInPound;
    /*one integer constructor for dog class,
    * similar to a method, but it is not a method.
    * it determines how to instantiate the class.*/
    public Dog(int w){
        weightInPound = w;
    }
    /*non static method, a.k.a instance method.
    * if the method is going to be invoked by an instance
    * of the class, then it should be non-static.
    * if the method needs to use "my instance variables",
    * the method must be non-static*/
    public void makeNoise(){
        if (weightInPound < 20){
            System.out.println("yip");
        }else if (weightInPound < 50){
            System.out.println("bark.");
        }else{
            System.out.println("woooooof!");
        }
    }
}

DogLauncher.java

package hello_pkg;

public class DogLauncher {
    public static void main(String[] args){
        Dog d = new Dog(60);
        d.makeNoise();
    }

你可能感兴趣的:(Java)