[Java Review] 3: Object oriented programming

The following notes are based on the book: << Head First JAVA >> and video series: 手把手教你用Java基础教程 - 北京尚学堂 - 马士兵

Process - oriented programming
  • divde into processes
  • process by process
Object - oriented programming
  • divide into objects(tools)
  • realized by methods within a object
  • everthing in java is a object
  • Resuseable, Extensibility, easy to maintain and replace
Object and class
  • A object is an instance of a class.
  • A class is a template.
  • A object has attribute (member variable) and method.

java object explain

Relationships between classes (more later)
  • Inheritance
  • Association
  • Composition
  • Aggregation
  • Realization

Class-Diagram-Relationships

Define a class
  • Member variables can have a default.
  • otherwise java automatically init them (0, ‘0’, null).
1
2
3
4
5
6
7
8
9
public class Person(){
// member varibles
int id;
int age = 20;

public void sayHello(){
System.out.print('hello!');
}
}
Construction method
  • same name as class
  • no return, no void
1
2
3
4
5
6
7
8
9
public class Person{
int id;
int age = 20;

Person(int _id, int _age){
id = _id;
age = _age;
}
}
Default construction method
  • if no construction method is specified, default is used:
1
Person(){}
  • otherwise, default is overridden.
Overload construction method
  • Mutiple construction methods are allowed.
  • Method names have to be same (same as class name).
  • Can be distinguished by either:
    • number of parameters
    • paremeters’ types
1
2
3
4
5
6
7
8
// init person with specific id and age
Person(int _id, int _age){ id = _id; age = _age;}

// init person with specific id and default age (set to 20 mannually)
Person(int _id){ id = _id; age = 20;}

// init person with default age and default id
Person(){id = _id; age = _age;}
Overload normal method
  • same as above
  • Method return type also need to be same.
Reference type
  • takes two space in ram. (address and instance)
  • address is saved in stack ram.
  • new instance is saved in heap ram.
  • method does not use space until called!
1
2
String s; // create a reference type, is
s = new String('hello world'); // create a instance, assigned to s
Rule of naming
  • Class names begin with upper case.
  • Variable names and method names begin with lower case.
  • Use camelSignal if a name contains mutiple words.
0%