Classes are the basic building blocks of java program. A class includes fields, methods and comments.
/**
* javadoc comment
* Tree.java
* @author xyzcoder
*/
public class Tree { //keyword public means the class can be accessed by any other classes.
String name; //field, default value is null
/*
the tree is 5 feet
*/
protected int size() {return 5;} //method
}
Java class is defined in *.java file. More than one classes can be defined in the same java file. In that case, only one class can be public, and the file name need to match the public class name.
javac command is used to compile the .java code into bytecode, the result is .class files.
OCAJP>javac Class.java
OCAJP>cat Class.java
class Class{}
class Class2{}
class Class3{}
OCAJP>mv Class.java Class2.java
OCAJP>javac Class2.java
OCAJP>vi Class2.java
OCAJP>cat Class2.java
public class Class{}
class Class2{}
class Class3{}
OCAJP>javac Class2.java
Class2.java:1: error: class Class is public, should be declared in a file named Class.java
public class Class{}
^
1 error
OCAJP>vi Class2.java
OCAJP>cat Class2.java
public class Class{}
public class Class2{}
class Class3{}
OCAJP>javac Class2.java
Class2.java:1: error: class Class is public, should be declared in a file named Class.java
public class Class{}
^
1 error
OCAJP>mv Class2.java Class.java
OCAJP>javac Class.java
Class.java:2: error: class Class2 is public, should be declared in a file named Class2.java
public class Class2{}
^
1 error
OCAJP>vi Class.java
OCAJP>cat Class.java
public class Class{}
class Class2{}
class Class3{}
OCAJP>javac Class.java
OCAJP>ls Class*
Class.class Class.java Class2.class Class3.class
Back OCAJP