//method public String getName() { return name; } }
Class Fields
1 2
private String name;//private refers this variable can only access by it's own method. privatedouble salary;
Class constructor
1 2 3 4 5 6 7 8 9 10
publicEmployee(String n , double s) { name =n; salary =s;
//use constructor: new Employee("Jamws Bond",10000); //there can be serveral constructors in a class. }
Constructor
Java offers several mechanisms of constructing a new object.
This function is called as overloading. If there’s several functions with same name but different parameters , the complicator will choose a function .This called overloading resolution .
Ok, let’s see constructor.
Default field initialize:
1
Employee John = new Employee();
All the number will be 0, boolean will be false, object reference will be null.
Caution: This is not a good habit to initialize a new object with default field.
Constructor without parameter:
1 2 3 4 5 6
publicEmployee() { name =""; salary =0; hireDay =LocalDate.now(); }
Explicit field initialize
You can initialize field value in the declaration of a class.
Before using constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassEmployee { private String name =" "; privatestaticint nextId; privateint id = assignId();
privatestaticintassignId() { int r= nextId; nextId++; return r; } }
Calling another constructor
Use this to call another constructor when you are just using a constructor.
//Use initialization block { id = nextId; nextId++; } }
Summary
The Steps of Calling constrictor
1.If the constructor calls another, construct by that one.
2.a. All the field will be initialized by default.
b. According to the order in class defination, execute field initialize function and initialization block.
Class Operation
Use var to state a local variable
1
var harry = new Employee("Hurry",5000);
Use clone to return a copy of an object
1
return (Date) hireDay.clone();
Tips: a private field is accessible to an object of same class.
Static
A field or method which is defined as static means there is ONLY ONE in the same class.
1
publicstaticfinaldouble PI = 3.141592653;
A static method do not use an object. Such as:
1
Math.pow(10,3);
A static method can not access fields in an object ,but can access static field.
Use static initialization block
1 2 3 4 5
static { var generator = new Radom(); nextId = generator.nextInt(10000); }
Main method
A class can have a main method, but it will not come into effect. It is used to TEST a class.
Class Date
1 2 3 4 5 6
System.out.println(new Date()); String s = new Date.toString(); Date deadline;//However,this variable does not refer to any object. deadline = new Date();//ok. deadline = null;// refer to no object deadline = birthday;//they refer to the same object
package com.msfasr.java_startup;//The code is included in a package
import java.util.Scanner;//Inport Scanner for input
publicclassHelloWorld{//The main method is contained in a class publicstaticvoidmain(String[] args){//Be aware of the define of the main method System.out.println("Hello,world"); } }
Class Methods
1 2 3 4 5 6 7 8 9
publicstaticvoidprintCalendar() { ...... }//static method, do not operate fields
publicvoidchangeFormat() { ...... }//this method must based on an object
Method parameters
Java programming language can only Call by value .
However, when the parameter is an OBJECT , methods can change values of OBJECTS.
In Class Array with dynamic binding, we created an array contains Manager and Employee. However, the array is a Employee array, so we need to use Forced type conversion to convert a Employee object to a Manager object.
1
Manager boss = (Manager)staff[0];
But, when you are trying to convert a object from top to bottom, it won’t work.
1 2 3 4 5 6 7 8 9 10
Manager boss = (Manager)staff[1];// Not work
//So,we can avoid this case by using: if(staff[1] instanceof Manager) {
boss = (Manager)staff[1];
//...... }
Abstract Class
Abstract class is a sort of class that is more general. Such as Person can contain Employee and Student.
Consistency : If x and y did not change , the equality do not change.
x.equals(null) == false.
Advice of designing an equals method
See Core Java Vol.1 , 11th edition , Page 178.
Hash code
hashcode() : returns an integer , the hash code , that refers the object.
Object.hash(Obj1,Obj2,……,ObjN) ;
Object.hashcode(Obj);
toString
Object.toString(); Print a string that consist of all fields. Needs you write yourself.
ArrayList
1 2 3 4 5 6 7
ArrayList<Employee> staff = new ArrayList<Employee>();
//add an object: staff.add(Object); staff.add(new Employee(......));
staff.size();//returns the number of objects.
Compare: ArrayList and Array
1 2 3 4
stuff.set(i,harry);//stuff[i] = hurry Employee ep = stuff.get(i);// Employee ep = stuff[i] stuff.add(i,E);//insert E to position i , move the rest. stuff.remove(i);//delete Element at position i, move the rest
Object Wrapper
Wrapper class is a sort of class that corresponding to basic data types.
Such as:
1 2 3
var list = new ArrayList<Integer>(); list.add(3); //Autoboxing int n = list.get(i); //Autounboxing
publicstaticvoidmain(String[] args){ var staff = new Employee[3]; staff[0] = new Employee("Mark",12000,2020,1,20); staff[1] = new Employee("Lin",10000,2020,1,20); staff[2] = new Employee("Coal",41230,2020,1,20); Arrays.sort(staff); return;
var listener = newTimePrinter; var timer = newTimer(1000,listener); //...... //timer每1000毫秒通知实现了ActionListener接口的类,这个类就会实现接口提供的函数actionPerformed,完成一个回调。
Lambda 表达式
一种自定义代码块,用于实现某些计算或执行某些函数
1 2 3 4 5 6 7 8 9 10 11 12
//比如,要计算a.length() - b.length() (String a, String b) ->a.length()-b.length() //或者: (String a, String b)-> { if(a.length<b.length) return-1; //...... } //执行函数: var timer = newTimer(1000,event ->System.out.println(event))
Scanner sc = new Scanner(System.in);//new a scanner String name = sc.nextLine();//Get a line int age = sc.nextInt();//Get the next int sc.close();//Close the scanner when used,or it will report an error.
Other measures
1 2 3 4 5
String nextLine();//read next line; String next();//read next word, use blank as separator. intnextInt();//read next int booleanhasNext();//if there's words in line booleanhasNextInt();
Read files
1 2 3
Scanner sc = new Scanner("Path",StandardCharsets.UTF_8);//read file PrintWriter out = new PrintWriter("Path",StandardCharsets.UTF_8);//Write file out.print();//Warning: this method will rewrite the file!!!
Output (System.out)
1 2 3 4
System.out.println(1111);//Print and return System.out.print(1111);//Print without returning System.out.write(2222);//byte output System.out.printf("%+8.3f\n", 3.14);//Print according to format
Java variable :
Variable types
Variable type
value
int
4byte,-2147483648~2147483647
short
2byte
long
8byte
byte
1byte
float
4byte
double
8byte
char(UTF-16)
16byte(UTF-16 character )
boolean
true/false
Caution: A variable must be initialized ,or the compiler will put an ERROR.
In java, key word final refers a variable is constant.
enum:
1 2
enum Size {Small,Medium};//enum is a CLASS! Size s = Size.Small;//it can only use values defined above.
str.length(); //return length str.blank(); // judge if the string is empty str.join("/",str1,str2,str3......);// use / as separator , combine strings String.format("%f",a);//returns a String with format
Big numbers
1 2 3 4
BigInteger; BigDecimal; num1.add(num2); //use add subtract multiply devide mod
Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int[] a = newint[100]; int[] a = newint[n]; int[] a = {1,3,7,7,9}; a = newint[] {1,3,5,7,9}; a.length(); Array.sort(a); Array.binarySearch(xxx[] a,xxx v); Array.binarySearch(xxx[] a,int start,int end,xxx v); Array.fill(xxx[] a,xxx v); int a[][] = newint[1][3]; int[] temp = a[1]; a[1]=a[2]; a[2]=temp;//exchange 2 lines int[][] feb = newint[100][]; for(int n=0;n<100;n++) feb[n]=newint[n+1];//regard feb[n] as an array name.
Array copy:
1 2 3 4
int[] a = {1}; int[] b = a; a[0]=5;//now,b[0] is also 5 int[] ca = Arrays.copyOf(a,5);//then we get a new array, the size is 5.