Class, field and method
Constructor
- Same name with class
- No return value
Person (String name, int age) {
this.name = name;
this.age = age;
}
Access fields or methods
Person p = new Person();
System.out.println(p.name);
p.sayHello();
Overload
Several methods have the same name. They can be recognized while compiling.
Their signatures must be different:
- Number of args
- Type of args
this
Access fields and method in methods and constructor.
- Can be used to distinguish fields and local variable
this.name = name
- Can be used to call another constructor
this(0,"");
inside a constructor- must be the first statement
void sayHello(){
System.out.println("Hello! My name is " + name);
}
// is equivalent to
void sayHello(){
System.out.println("Hello! My name is " + this.name);
}
Inheritance
- Subclass
- Can inherit and modify status and actions from superclass
- Can add new status and actions
- Superclass
Java support single inheritance. A class can only have one superclass.
Inheritance is achieved by extends
. If no extends
, this class is the subclass of java.lang.Object
by default.
class Student extends Person {
String school;
int score;
boolean isGood(){return score>80;}
}
Override
@Qverride
void sayHello(){
System.out.println("Hello! I'm a Student. My name is " + name);
}
Overload
Overload will be a new added method.
Super
Can use super
to access field and field of its superclass. (this
can be used too)
- To distinguish fields and methods with the same name between superclass and subclass
- Even when the fields of superclass have been overridden. (
super
is required instead ofthis
)
- Even when the fields of superclass have been overridden. (
- Can be used to utilize constructor of superclass
- Constructor of superclass cannot be inherited.
- In the constructor of subclass, can use
super
to call constructor of superclass super()
must be the first statement
void sayHello(){
super.sayHello();
System.out.println("I'm a Student.");
}
Student(String name, int age, String school){
super(name, age);
this.school = school;
}
- An object of subclass can be an object of superclass
- An object of superclass cannot be an object of subclass
- If an arg is an object of superclass, then an object of subclass can be used here
- Can use casting to convert reference of a superclass object to a reference of a subclass object
Person p = new Person();
Student s = new Student();
Person p2 = new Student();
Student s2 = (Student) p2; // valid
Student s3 = (Student) p; // cannot be executed while compiling
Person [] manyp = new Person[ 100 ];
manyp[0] = new Person();
manyp[1] = new Student(); // valid
Packages
- Namespace and path(folder)
- Classes in the same package can access each other by default
- Root path is determined by
CLASSPATH
To avoid conflict of namespace and names.
package pkg1 [.pkg2];
import
Java compiler will import java.lang.*
by default.
import pkg1 [.pkg2...].(classname |*);
import java.util.Date;
// so java.util.Date in program can be simplified as Date
// all classes on this level, not next level
import java.awt.*;
import java.awt.event.*;
Compile and run
javac -d destination_folder filename.java
javac -d . pk\*.java
// run class with main inside
java pk.Test
java -classpath classpath_name pk.Test
Modifiers
- Access modifiers
- public/private …
- Other
- abstract
Can be used on class and class members (fields and methods)
Modifiers | Same Class | Same package | Subclass in different pkg | non subclass in different pkg |
---|---|---|---|---|
private | Yes | |||
default | Yes | Yes | ||
protected | Yes | Yes | Yes | |
public | Yes | Yes | Yes | Yes |
public
or default for class- setter and getter
private
for fields- Use method
setxxx
andgetxxx
to set and get fields
Other
Other | meaning | for class? | for member? | for local var? |
---|---|---|---|---|
static | static, not instance, class | for inner class | Yes | |
final | final, cannot be changed | Yes | Yes | Yes |
abstract | abstract, cannot be instantiazed | Yes | Yes |
static:
- The field for class, don’t belong to any instance
- It’s saved in the memory area for class, instead of instance
- Class variable can be accessed using class name or instance. Results are the same.
Person.totalNum
orp.totalNum
- Like
in
andout
object ofSystem
class - Can be used as global variables
- Cannot use
this
orsuper
(because they are for an instance) in a static method import static java.lang.System.*;
So can useout.println();
final
- final class
- This class cannot be inherited, no subclass
- final method
- This method cannot be overriden by subclass
- final field and local variable
- Their value cannot be changed (assign value once and only once)
static final
will give a constantInteger.MAX_VALUE
,Math.PI
- Assign value
- No initial value given for
static final
, following will be assigned- num: 0
- boolean: false
- reference: null
- If a
final
field (Notstatic
), must be assigned value once and only once, cannot miss- Assign while defining
- Assign in every constructor
final
local var must be assigned value once and only once. The value may not be constant, but its value won’t change while it exists.
- No initial value given for
abstract
- abstract class
- cannot be instantiated (new)
- abstract method
- Abstract method defined a uniform interface for all subclass
- Only need declaration, not realization, use semicolon
( ; )
not{}
abstract returnType abstractMethod( [paramlist] );
- If a class has abstract method, it must be abstract class.
- An abstract class is unnecessary to have abstract methods
- Abstract method must be used(override) in subclass, otherwise the subclass will still be abstract
abstract class E{
public abstract void show();
}
class F extends E{
public void show(){
System.out.print("test all FFFF \n");
}
}
class G extends E{
public void show(){
System.out.print("test all GGGG \n");
}
}
public class main
{
public static void main(String[] args)throws InterruptedException {
E p = new F();
p.show();
E q = new G();
q.show();
}
}
Interface
- A kind of agreement
- Declare:
interface
- All methods would be
public abstract
automatically
- All methods would be
- Use:
implements
- Multi inheritance
- Unrelated with class inheritance
- Declare:
- ‘Interface oriented programming’
- Achieve the same action between several unrelated classes
- Point out methods that several classes need to realize
- Can understand the interface of an object, don’t need to know its class.
- Reference type
Example
- Interface: Flyable
- Class: Bird(<-Animal), Plane(<-Vehicle), Superman(<-Animal)
-
Flyable f = new Bird();
- Use
public
for methods while realization - Interface names should be end with ‘able or ‘ible’
- Can have multi super interfaces
Declaration
[public] interface Collection [extends listOfSuperInterface] {
void add (Object obj);
void delete (Object obj);
Object find (Object obj);
int size ( );
}
Usage
class FIFOQueue implements collection{
public void add(Object obj){
...
}
public void delete(Object obj){
...
}
public Object find(Object obj){
...
}
public int currentCount{
...
}
}
reference
Collection c = new FIFOQueue();
c.add(obj);
constant
Declaration
type NAME = value;
- The constant defined in a interface can be shared by the classes using this interface.
- Same as
#define
in C andconst
in C++ - the constant will be
public, static, final
- Same as
enum
Declaration
enum Light{ Red, Yellow, Green}
Usage
Light light = Light.Red;
switch( light ){case Red:... Break;}
- The
case
should not be followed byLight.Red
Interface in Java8
The interface members can be
- static method
- non abstract
- default method
- provide a default version. Subclasses don’t need to write again in implements.
Syntax summary
class
[public] [abstact|final] class className[extends superclassName]
[implements InterfaceNameList]{
//declare a class
[public | protected | private] [static] [final] [transient] [volatile]type variableName;
//declare variable, can be multiple
[public | protected | private] [static] [final | abstract] [native] [synchronized]
returnType methodName( [paramList] ) //declare method, can be multiple
[throws exceptionList]{
statements
}
}
interface
[public] interface InterfaceName[extends superInterfaceList]{ //declaration of interface
type constantName= Value; //constants
returnType methodName( [paramList] ); //methods
}
Fixed declaration
// constructor
className([paramlist]){
...
}
// main()
public static void main( String args[]){
...
}
// finailize()
protected void finalize() throws throwable{
...
}
Source file
package packageName; //the package which the file belongs to,0 or 1
import packageName.[className|*]; //0 or more
public classDefinition//public class declaration, 0 or 1
interfaceDefinition and classDefinition//interface or class declaration, 0 or more
- The name of source file must the the same as the public class name
- At most 1
package
statement orpublic
class