Object-oriented Programming
What is OOP?
It is quite normal to be ask “What is OOP” in the interview.
According to its definition in Wikipedia
Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
In short, an object has fields
and methods
.
3 properties of an object:
- Behavior: method and process.
- State: how will it respond when calling the method.
- Identity: identify object with same behavior and state.
Class
The program use Class to contruct an instance of object.
Data stores in instance field and method is used to operate data.
Relationship
3 Types of relationships
- Dependence: uses-a, method in A use the method in B
- Aggregation: has-a, A has object B
- Inheritance: is-a, A is a onject of B
Encapsulation 封装
Protect the field. The field cannot be modified directly using assignment.
To Get & Set
- a private field
- a public acessor / getter
- a public settor
Final
Set a fild to be final will require initialization in constructor. It cannot be modified later.(cannot set)
1 | class Emlpoyee |
Constructor
Overloading
Methods have same name but difference perameters.
Static
Static saves memory to make progrm memory efficient.
Field
Every object of this class shares the same static field, whereas every object has its onw copy of non-static field.
When there is no object of this class, the static field still exist as it belong to class, not belong to object.
Every object can set value of this static field, so try not to use public
if possible.
Constant / Final
It can be call directly using class without contruct any instance.
1 | public class Math |
Call using
1 | Math.PI; |
Method
Call using class without instance.
1 | Math.pow(1,2); |
Parameter of Method
Call by
- value: passing value to method
- reference: passing address
- name: not used in java
Call by Value
Java are mainly using call by value.
1 | public void triple(double x) |
Call by Reference
To use call by reference, passing an object to parameter
1 | public void triple(Employee x) |
Package
import
Use * to import every class under a package. But cannot use java.*
to import every package.
Static import allow using method without prename
1 | import java.util.*; |
Construct
Use package packagename
at the beginning. Make sure the file structure is the same as the index.
1 | package com.horstmann.corejave; //cd com/horstmann/corejave |
Object-oriented Programming
http://isa-lai.com/blog/2021/08/27/object-oriented-programming/