Deeper understanding
Variable
- field:
- a part of object,
- saved in heap
- assigned value automatically
public, private, static, final
- local var:
- in method
- stored in stack
- must be assigned value explicitly
- cannot use access modifiers and
static - can be
final
- primitive type
- int, String
- pass value
- reference type
- class, interface, array
- pass ref
Return
- Return primitive type
- Return ref type
Object getNewObject()
{
Object obj = new Object();
return obj;
}
Object p = getNewObject();
Polymorphism
- While compiling
- overload (different methods with the same name)
- e.g.
p.sayHello()andp.sayHello("Wang")
- While running
- override (subclass overrides the superclass method)
- dynamic binding, or called virtual method invoking
- For all non
finalmethods
- For all non
- Program will use subclass method correctly
- Will call the method belonging to that instance (Student instead of Person)
Upcasting
- Treat subclass as superclass
Person p = new Student();void fun(Person p){...}andfun(new Student());
instanceof
instanceofdetermines whether an object is an instance of a class- Return a boolean
if a instanceof Integer
non-virtual methods
- normal methods are virtual methods (depending on the objects)
static,privateare not virtual methodstaticis class method, not instance- Subclass cannot see
privatemethods
static: based on the declared type, unrelated to the object typeShape s = new Circle()s.draw();will call thestaticmethoddrawof classShape
private: Subclass cannot see.final: Subclass cannot override it.
Constructor and initialization
thiscall the constructor of this classsupercall the constructor of superclassthisorsupermust be the first statement, and only one- If none, compiler will add
super()automatically
- If none, compiler will add
Initialization
p = new Person(){
{
age = 18; name = "Jack";
}
};
- Assign values to fields
- Double
{ { } }
Instance Initializers
{...}in class will be conducted before constructor{...}static {...}in class will be conducted before{...}
Constructor
- Call
thisorsuperconstructor until the highest (Object) - Assign values to fields
- Conduct following statements in constructor
Garbage deletion and collection
- Do the garbage collection:
System.gc() finalize()will release system resourcesprotected void finalize() throw Throwable{}- Subclass
finalize()should call superclassfinalized()
Close file and clean
For java.lang.AutoCloseable object, will call close()
try (Scanner scanner = new Scanner(...)){
...
}
Inner class and anonymous class
- Inner class
- put class definition inside a class
- Name must be different with outer class
- Simple usage inside the outer class
- Other place:
outerClassName.innerClassName xx = outerObjectName.new innerClassName - Inside inner class
outerClassName.this.field
- Anonymous class
Lambda expression
- Like an interface
(params) ->(result)- An instance of anonymous class
- only one function inside
- Interface
@FunctionalInterfaceinterface Fun {double fun( double x);}
Example
(String s) -> s.length()x -> x*x() -> {System.out.println("aaa");}new Thread(()-> System.out.println("aaa")).start();- Integral:
double d = Integral(x->Math.sin(x),0,Math.PI,1e-5);interface Fun {double fun( double x);}double d = Integral(new Fun(){public double fun(double x){return Math.sin(x);}},0,Math.PI,1e-5);
- Sort:
Comparator<Person> compareAge = (p1,p2) -> p1.age-p2.age; Array.sort(people,compareAge);Array.sort(people, (p1,p2)->(int) (p1.score-p2.score));Array.sort(people, (p1,p2)-> p1.name.compareTo(p2.name));
New syntax
primitive type to Object (ref type)
inttoInteger- 8 in total
BooleanByte,Short,Integer,Long,Float,DoubleCharacter
Integer I = new Integer(10);
Easier
- Boxing:
Integer I = 10; - Unboxing:
int i = I; - For array:
Object[] ary = {1,"aaa"};1will be automatically converted.
enum
Can add fields, methods, constructor
Example
enum Light {R,L,Y};Light l = Light.R;
enum Direction
{
EAST("E",1), SOUTH("S",2),
WEST("W",3), NORTH("N",4);
private Direction(String desc, int num){
this.desc=desc; this.num=num;
}
private String desc;
private int num;
public String getDesc(){ return desc; }
public int getNum(){ return num; }
}
Annotation
- Not comment
- Subclass of
java.lang.annotation.Annotation
Example
@override@Deprecated: outdated method@SuppressWarnings: No warning while compiling
Reference and pointer
References are safe pointers
- Pass address -> object (ref type)
- Pointer operation -> array
- Function pointer -> interface, Lambda expression
- Pointer to node -> reference of objects
- Use JNI
- Interface with other lang
Equal or not equal
- Primitive: value
- Compare after conversion (
intandfloat) - Don’t use
==forfloatDouble.NAN == Double.NANisfalse
- Cannot compare
booleanwithint - -128 to 127: 2 boxing int will equal to each other
- Compare after conversion (
- enum
- Do single instantiation inside, can estimate directly
- Reference: ref
- Whether two ref are the same
- If need to estimate whether contents are the same: override
equalsmethod - If need to override
equalsmethod: better overridehashCode()
- String (ref type)
- Need to use
equalsmethod, not== - Constant String literal can use
==String hello = "Hello";: truehello == new String("Hello");: false
"String lo = "lo";"Hel"+lois not constant"Hel"+"lo"is a constant("Hel"+lo).intern())is constant
- Need to use
Exception
throw exceptionObject;
try{
} catch(ExceptionClassName FormParamsName){
}catch(IndexOutOfBoundsException ex){
}catch(IOException ex){
}catch(NumberFormatException ex){
}finally {
}
Exception class
Constructor
public Exception();public Exception(String message);Exception(String message, Throwable cause);
Method
getMessage()getCause()printStackTrace()
Checked exception
- RuntimeException and subclass don’t need to be dealt with.
IndexOutOfBoundsException
- Checked exception must be dealt with
catchorthrows- If a method in superclass declared
throwsexception, the subclass overriding that method mustthrowsexception (a more specific one)
public static void readFile()throws IOException {
}
A compiler sugar:
try(Type varName = new Type()){
}
// finally{var.close();} will be added automatically
Pass exception
- Throw it again:
throw e; - Generate a new exception and throw it
throw new Exception("some msg");
- Generate a new exception and throw it with current exception
throw new Exception("some msg",e);- get inner exception with
e.getCause()
User-defined exception
class DataHouseException extends Exception {
public DataHouseException( String message){
super(message);
}
}
class AppException extends Exception {
public AppException( String message){
super(message);
}
public AppException( String message, Exception cause){
super(message,cause);
}
}
Assertion and Test
assert expression;
assert expression: msg;
Example:
class Assertion {
public static void main(String[] args) {
assert hypotenuse(3,4) == 5 : "incorrect";
}
static double hypotenuse(double x, double y) {
return Math.sqrt( x*x +y*y);
}
}
Usage
java -ea -classpath .Assertion
Test
Use JUnit
Eclipse:
- project, right click __ new __ Junit Test case
- project, right click __ Run as __ Junit Test
In test file
public class testHello1 {
@Test
public void testSum1() {
HelloWorld a = new HelloWorld();
assertEquals(a.sum(1,2), 3);
assertNull(params);
fail("message");
}
}
Error
- Syntax error
- Runtime error
- Logic error
- debug
- unit test
In IDE, right click project, debug as to debug perspective
3 tools
- breakpoint,
Ctrl+Shift+B - trace
- conduct line by line:
F5 - conduct step over (not into functions):
F6 - jump out functions:
F7 - conduct to cursor:
Ctrl+R
- conduct line by line:
- watch
- Mouse
- Quick: right click,
Inspector - Add: right click,
Watch
