Process-oriented: Focus on step-by-step, considering the process of completing the function (doing it step by step by oneself)
Focus on modular division (finding people to distribute tasks to solve tasks)
Summary
Object-oriented advantages: extensible, maintainable, high flexibility, low coupling of programs
Object-oriented disadvantages: performance is relatively worse than process-oriented
💪 Method Characteristics#
- Static methods are called using the class name, constructor methods create instances when objects are called, member methods are called by objects
- Constructor
- Declaration: access modifier method name (parameter list) {method body}; the method name must match the class name
- If there is no constructor in the class, a default no-argument constructor exists; if you write your own, the default one is gone; generally, after writing a constructor, you will write a no-argument one
- Only member methods can directly access member properties; static methods cannot access member variables (methods that need member variables should be defined as member methods)
- Member methods can access static variables
🎗 Relationship Between Classes and Objects#
- Class: A standard objective description of things
- Object: Everything is an object, a specific individual that meets class standards
Object Usage#
Instantiate an object: Student s1 = new Student();
Get and set member properties through get and set methods
🔌 JavaBean#
JavaBean
is a reusable component written in Java
, which is a class (the class must be concrete, public, and have a no-argument constructor)
- Private member variables
- Provide
get
andset
methods externally - Explicitly declare no-argument and full-argument constructors
- The role of
get
andset
methods- Protect member variables
- Intercept
🎉 Memory Process of Instantiation#
- Load client class
main()
method pushed onto the stack- Load server class
- Call constructor
- Allocate space in heap memory, initialize the instantiated object
- Constructor pops off the stack, the instantiated object is assigned to the variable
💥 Exceptions#
- Compile-time exceptions
- Runtime exceptions
- Null pointer exception (when accessing member variables with
null
) - Array index out of bounds
- Type conversion exception
- Null pointer exception (when accessing member variables with
⚠️ Common Mistakes#
- Distinguish between member methods and constructors: look for no return value (constructors have no return value)
- Objects can call static variables;
javac
will change it to call static variables using the class name during compilation (so null pointers do not affect) - Static methods cannot call member variables
👈 this#
The first member variable in an object, which saves the memory address of the current object (cannot appear in static methods)
Function#
- Used in member methods/constructors to distinguish between similarly named member variables and local variables
- Overload to call the current class's parameterized constructor
Must be on the first line of the current constructor's method body - Chained calls
⚙️ static#
Modifier used to mark static properties; if not used static
, it is a member property
Function#
- Static variables
- Static methods
- Static code blocks
Cannot be called; called when the program loads (runs before themain()
method); executed only once
Code block: unnamed method, automatically called
A class's static properties will only load that class into memory when accessed.
Instance statement blocks can be seen as unnamed member methods.
📦 Encapsulation#
Combine all components together, and also hide data through access control modifiers, controlling the extent of user modifications to class data.
Proper encapsulation can make code easier to understand, easier to maintain, and improve code security.
Importing Packages#
Placed below package
and above class
Static import
Import a specific static variable from a class
Access Control#
Scope | public | protected | default | private |
---|---|---|---|---|
Same Class | ✔️ | ✔️ | ✔️ | ✔️ |
Same Package | ✔️ | ✔️ | ✔️ | ❌ |
Subclass | ✔️ | ✔️ | ❌ | ❌ |
Global | ✔️ | ❌ | ❌ | ❌ |
🧬 Inheritance#
Deriving a new class from an existing class. This class often contains the characteristics of the parent class and can also add unique properties.
📝 Overriding#
Must have an inheritance relationship
- Method name, parameter list, return value must be the same
- Cannot have lower access permissions than the original method
- Cannot have broader exceptions than the original method
Difference Between Overriding and Overloading#
Annotations#
Source annotations
Compile-time annotations
Runtime annotations
🛑 final#
Can be placed on
- Class
- Variable
- Method
🌱 Polymorphism#
A parent class reference points to a subclass object
- Parent class
- Reference points to the reference data type
- Can find who it points to
- Subclass object creates an instance of a subclass
Using a reference type variable created from the parent class can find the subclass object
ParentClass variableName = new SubClass();
Upcasting (converting from subclass to parent class) is similar to automatic type conversion.
Non-member methods
Advantages#
- Reduces coupling
- Enhances extensibility, replaceability, and flexibility
Disadvantages#
Will lose subclass-specific properties
Member methods If the subclass overrides the parent class's member method, it will call the subclass's member properties.
Non-member methods Call the parent class method.
public class Poly {
public static void main(String[] args) {
Sup sub = new Sub();
// 2
System.out.println(sub.age);
sub.m1();
// Son m2
sub.m2();
// sub.m3();
}
}
class Sup{
int age = 2;
public void m1(){
System.out.println("Father m1");
}
public void m2(){
System.out.println("Father m2");
}
}
class Sub extends Sup{
int age = 1;
public void m2(){
System.out.println("Son m2");
}
public void m3(){
System.out.println("Son m3");
}
}
instanceof#
Determines whether an object is instantiated from a certain class.
Downcasting (converting from parent class to subclass)
- Direct polymorphism
ParentClass variableName = new SubClass();
- Actual parameter formal parameter polymorphism
- Return value polymorphism
Method return value uses parent class declaration
Hidden Polymorphism#
When calling inherited member methods from the parent class using a subclass object, the context environment is polymorphic.
public class Poly_05 {
public static void main(String[] args) {
// Sup sup = new Sub();
// // 2 Parent class
// System.out.println(sup.age);
// // Parent class because subclass does not have
// sup.m1();
// // Subclass because overridden
// sup.m2();
// // Error, because parent class does not have, polymorphism will lose subclass-specific properties
// // sup.m3();
// // Downcasting
// Sub sub = (Sub) sup;
// // 1 Subclass
// System.out.println(sub.age);
// // Parent class inheritance
// sub.m1();
// // Subclass because subclass has
// sub.m2();
// // Subclass, but did not use polymorphism
// sub.m3();
Sub sub = new Sub();
sub.m1();
}
}
class Sup {
int age = 2;
public void m1() {
/**
* this : is the first member variable in the object, saving the memory address of the current object
*
* since this saves the memory address of the current object, the type of this can be the current class type or the parent class type
*
* wherever this is written, that class is the current class, so the current class is Sup and the parent class is Object
*
* because this can call all properties in the current class without losing anything, so this is of type Sup
*
* Sup this;
*
* this : which object calls this member method, this points to whom
*
* Ultimately, it is the Sub that calls the m1 method, so this points to Sub
*
* Sup this = Sub;
*/
// System.out.println("Parent class m1");
System.out.println(this);
// 2 Parent class
System.out.println(this.age);
System.out.println(this.sakjdkashdhqwrjnfaksf);
System.out.println(age);
// Subclass
m2();
// Error
// m3();
}
public void m2() {
System.out.println("Parent class m2");
}
}
class Sub extends Sup {
int age = 1;
public void m2() {
System.out.println("Subclass m2");
}
public void m3() {
System.out.println("Subclass m3");
}
}
🐘 Abstraction#
abstract
modifier is used to modify abstract classes and abstract methods.
A class modified by abstract
is an abstract class, and abstract classes cannot create objects; they are generally used for inheritance.
Methods modified by abstract
are abstract methods. These methods have no method body and do not implement functionality, allowing different subclasses to implement the method.
Abstract methods must be in abstract classes, and abstract classes can have normal methods.
An abstract class can be seen as a special class that just cannot create objects.
abstract
and final
cannot appear simultaneously.
- If a subclass inherits an abstract class, it must implement all abstract methods; otherwise, the subclass needs to be modified with
abstract
. - Abstract classes inheriting abstract classes need to implement 0 to N abstract methods.
- Ordinary classes inheriting abstract classes need to implement all methods.
👄 Interface#
interface
keyword
Before 1.8, interfaces were completely abstract, only allowing abstract methods and constants (psf
).
In interfaces, there are only constants, no variables, and psf
can be omitted, with access control defaulting to public
.
The abstract
keyword for abstract methods can be omitted.
interface A{
int age = 1;
// Default method
default void dmethod(){
System.out.println("Default method");
}
}
class B{
void m(){
System.out.println(A.age);
}
}
🌌 Object#
Object
is the root class provided by Java; all classes directly or indirectly inherit from Object
.
java.lang.Object
is in the java.lang
package; all classes in the core package do not need to be imported.
toString#
equals#
==
compares values for basic types, compares addresses for reference types.
==
is the default underlying implementation of equal()
.
The default equals()
compares addresses.
finalize#
JVM is cross-platform, multi-threaded, object-oriented, and has automatic garbage collection.
Garbage becomes an object when there are no references pointing to it.
When garbage is collected, the object's finalize()
method is automatically called; it is called when the object's life ends.
System.gc()
allows programmers to suggest that the JVM perform garbage collection.
🔗 Relationships Between Classes#
For details on the relationships between classes, see here
🧩 Inner Classes#
Member Inner Class#
class A{
class B{
}
}
Equivalent to a member variable; cannot have static declarations.
Inner classes can use access control modifiers.
Can access the private properties (marked as private
) of the outer class.
Member inner classes can directly access all data of the outer class.
At this point, the full class name of class B
is A$B
.
Static Inner Class#
class A{
private int a = 1;
private static int b = 1;
static class B{
int c = 1;
static int d = 1;
public void method(){
// System.out.print(a);
A aaa = new A();
System.out.print(aaa.a);
System.out.print(b);
}
}
}
- Static inner classes can be seen as static variables.
- Static inner classes cannot directly access the member properties of the outer class.
- Static inner classes can declare any data (static/member).
- After creating an object of the outer class, can access the member properties of the outer class.
Local Inner Class#
- A class within a method is a local inner class.
- Local inner classes can be seen as local variables.
- If a local inner class accesses local variables in the outer method, those variables need to be marked as
final
; after 1.8,final
can be omitted. - Local inner classes cannot use access modifiers.
- Local inner classes cannot have static declarations.
class A{
void method(){
class B{
}
}
}
At this point, the full class name of class B
is A$1B
.
If the inner class name is duplicated, it will be outerClassName$2innerClassName
.
Anonymous Inner Class#
When a method's parameter requires passing a class object, an anonymous inner class can be used.
Syntax#
new InterfaceImplementation(){
// Body of the anonymous inner class
}
Implementing an interface has no constructor, so it is empty.
new ParentClassConstructor(arguments){
// Body of the anonymous inner class
}
Calling the parent class constructor can be with empty parameters or can pass parameters.
Example#
// Interface part
interface Product{
public double getPrice();
public String getName();
}
public class Anonymous{
public void test (Product p){
System.out.println(p.getName()+"--------"+p.getPrice());
}
public static void main(String[] args ){
Anonymous as = new Anonymous();
// Here, the interface is implemented and the abstract methods are implemented.
as.test(new Product(){
// Implementing methods
public double getPrice( ){
return 8888;
}
// Implementing methods
public String getName(){
return "I can do it ";
}
});
}
}
The above code is simple; it defines a class Anonymous
, which has a method test
. Then it creates an Anonymous
object and calls its instance method test()
.
However, when calling the test()
method, a Product
object must be passed in. But since Product
is an interface, an object cannot be created, so the interface must be implemented. Therefore, an anonymous inner class is used here to implement all abstract methods in the interface.
Purpose#
No need to implement the interface or inherit the abstract class. However, the advantage of using an anonymous inner class is evident; it reduces code and makes the code more concise.