Three Characteristics of Object-Oriented
- Encapsulation: encapsulation
- Inheritance: inheritance
- polymorphism
encapsulation
Class is a basic encapsulation
The benefits of packaging:
- Data Security: Ensuring Data Security
- Convenient Call: Provide a clear external interface to facilitate external calls
- Decoupling: Implementations within classes can be modified without affecting other classes
Computer host is an example of encapsulation. Hardware such as memory is encapsulated in the cabinet. It provides display interface, power interface and USB interface to the outside world. Adding a memory bar does not affect the use of the outside world.
Good encapsulation: Restrict the accessibility of classes and members as much as possible.
As far as code is concerned, the state information of the object is hidden inside and can not be accessed directly by the outside world, so it must be accessed through the methods provided by the outside world.
It can prevent unreasonable assignment (such as negative age assignment) and facilitate the control of attribute values.
See "shared bicycle" or "tragedy of the commons":
attribute
1. The member variable is set to private.
2. Provide public get/set method as accessor.
In the early years, a book translated field as "attribute", but now field is generally translated as "member variable". Membership variables do not necessarily have methodologies.
Example: The Genie class has two attributes: name and species.
class The evildoer { private String name; private String species; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } }
Shortcut keys for automatically generating attributes in Eclipse:
Right-click in the code (shortcut Ctrl+Alt+S)
->Source
->Generate Getters and Setters...
-> Full selection (or selection of fields/methods to be generated)
Access modifier
(For the time being, you don't have to understand everything, just focus on private)
Access modifier | Oneself | Same package | Same package | Different packages | Different packages | |
---|---|---|---|---|---|---|
inherit | Non-inheritance | inherit | Non-inheritance | |||
public | For everybody | ● | ● | ● | ● | ● |
protected | Subclass use, same package use | ● | ● | ● | ● | X |
(default) | Use in the same contract (not in writing) | ● | ● | ● | X | X |
private | For your own use | ● | X | X | X | X |
Membership Variables and Local Variables
Membership variables: variables defined in a class
Local variables: (1) variables defined in methods; (2) variables defined in compound statements for (int n: arr) {...}
public class variable { int Membership variables = 1; void m() { int local variable = 2; System.out.println("m():" + local variable + "," + Membership variables); } void m2() { int local variable = 3; System.out.println("m2():" + local variable + "," + Membership variables); for (int i = 0; i < 10; i++) { System.out.print(i + " "); } } public static void main(String[] args) { //Variable t = new variable (); t.m(); t.m2(); } }
The differences between member variables and local variables are as follows:
Membership variables | local variable | |
---|---|---|
Define location | Method memory | Inside the method, even in the statement |
Scope of action | The entire class is available | Available in methods, even within the scope of statements |
life cycle | Method call is born, method end disappears | Object creation is born and objects are recycled away |
Default values | With default values, the rules are the same as arrays | No default value, must be assigned manually |
Memory location | Stack (method calls into the stack, end out of the stack) | heap |
method
Method is the abstraction of class or object behavior. Functionally, the method is similar to a function.
Methods in Java cannot exist independently and must be written in classes.
Reference: Value Transfer
Java has only one way of passing parameters -- value passing.
The so-called value transfer is to pass a copy of the "actual parameter" into the method, and the "actual parameter" itself is not affected.
For example, swap:
public class PassParameter { static void swap(int a, int b) { int temp = a; a = b; b = temp; System.out.println("Internal: a = " + a + ", b = " + b); } public static void main(String[] args) { int x = 100, y = 200; System.out.println("Before Exchange:x = " + x + ", y = " + y); swap(x, y); // No exchange was successful. System.out.println("After exchange:x = " + x + ", y = " + y); } }
_The parameters obtained by swap are only copies of the parameters x and y. In fact, there are four variables.
Operation results:
Before swapping: x = 100, y = 200 Internal: a = 200, b = 100 After exchange: x = 100, y = 200
To exchange two-digit values, you can encapsulate them into classes, which are reference types, but are still "value passing" when passing parameters.
However, class variables are actually stored in object references. In the method, class variables are modified. It is not the memory of variables that changes, but the content of instance objects that they refer to.
public class PassParameter2 { static void swap(MyData data) { int temp = data.a; data.a = data.b; data.b = temp; } public static void main(String[] args) { MyData md = new MyData(); md.a = 100; md.b = 200; swap(md); System.out.println("md.a = " + md.a + ", md.b = " + md.b); } } class MyData { int a; int b; }
Note that it is not possible to assign objects of "class type" directly in a function, but only variables.
So you don't intend to assign strings through method calls.
For example:
public class TestMethod { void changeData(MyData2 md) { md = new MyData2(); } void changeStr(String s) { s = "new"; } public static void main(String[] args) { TestMethod t = new TestMethod(); MyData2 md2 = null; // Class object assignment in method t.changeData(md2); System.out.println("md = " + md2); // Method assigns strings String s = "used"; t.changeStr(s); System.out.println(s); } } class MyData2 { }
Operation results:
md = null //used
Construction method
The construction method is also called constructor, Constructor.
Role: Initialize an object, usually by assigning an initial value to a member variable.
Features: 1. No return value; 2. Method name must be the same as class name.
In fact, the return value of the constructor is implicit, that is, the object of the current class.
new is an object that actually calls its constructor.
Objects are generated before the constructor calls, but need to be returned by the constructor.
public class Classes and objects { public static void main(String[] args) { Tiger c = new Tiger(); } } class Tiger { public Tiger() { System.out.println("---Construction method---"); } }
Operation results:
- Construction method
Parametric-free construction method:
If there is no handwritten construction method, the system defaults to provide a "parametric construction method".
If the handwritten construction method is used, the system will no longer provide a parametric construction method.
Automatic generation of construction methods:
There is often a super() in the auto-generated constructor, which means that the parametric constructor of the parent class is called, and deletion can also be invoked.
class Tiger { private String name; public Tiger(String name) { super();// This code can be omitted to indicate that the parent class constructor is invoked // Membership variables and parameters have the same name. According to the proximity principle, name uses parameters and this means using member variables. this.name = name; } }
overload
1. Same method name
2. The parameter list is different:
a) The same parameter type and different number
b) The same number of parameters and different types
3. Overloading regardless of modifiers, return types, etc. (Method calls can ignore return values)
public class TestOverload { static void m(int a, int b) { System.out.println("m1"); } static void m(int a, double b) { System.out.println("m2"); } public static void main(String[] args) { m(1, 2); m(1, 2.0); } }
Static.static
static can be used to modify {classes, member variables, methods, code blocks} to indicate that these components belong to the "class itself" rather than the "instance".
Static variables
Membership variables are divided into:
|- Class variables (static)
|- Instance variables
Instances can be multiple, and each instance can have its own data.
There is only one class, and the variables modified by static belong to the class, and there is only one class, and multiple objects can be shared.
Example: Counting cats
public class Test Static variables { public static void main(String[] args) { Cat c1 = null; for (int i = 1; i <= 100; i++) { c1 = new Cat(); c1.count++; c1.countStatic++; } System.out.println(c1.count); System.out.println(c1.countStatic); Cat.countStatic++;// Static variables can be invoked directly through class names System.out.println(c1.countStatic); } } class Cat { static int countStatic = 1; int count = 1; }
Static method
Static methods do not belong to objects, they belong to classes.
Static subdivisions can be used without the need for new (instantiated objects).
The most famous static method is the main method.
Use of static methods: class name, static method name (parameter list);
Array.sort(...) is a static method that can be used without a new Array class.
package ah; public class Test Static method { public static void main(String[] args) { Dog.method Static method();// In other classes: class name calls // Non-static Method (Common Method): new Object Call Dog _dog = new Dog(); _dog.method General method(); } } class Dog { void method General method() { System.out.println("Dog: method General method"); } static void method Static method() { System.out.println("Dog: method Static method"); } }
If called in the current class, the class name can be omitted.
public class Test Static Method 2 { void method General method() { System.out.println("method General method"); } static void method Static method() { System.out.println("method Static method"); } // ----------------------------- public static void main(String[] args) { Test Static Method 2.method Static method();// In this class: class name call method Static method();// This class: direct calls // That is, their own non-static methods must also be new Test Static Method 2 _self = new Test Static Method 2(); _self.method General method(); } }
Static code block
Ordinary code blocks: Classes are executed when they are created (new), earlier than construction methods.
Static code blocks: Classes are executed when they are used, earlier than regular code blocks.
| When this class is first used, static code blocks are executed and will not be executed later.
public class Test Static code block { public static void main(String[] args) { Tiger _t = new Tiger(); } } class Tiger { public Tiger() { System.out.println("Construction method"); } { System.out.println("Ordinary code block"); } static { System.out.println("Static code block"); } }
Output results:
Static code block
Ordinary code block
Construction method
Typical use of static code blocks: assigning static member variables at one time.
Such as:
public class Test Static code block { public static void main(String[] args) { System.out.println(Driver.os); } } class Driver { static String os; static { if ("Windows 10".equals(System.getProperty("os.name"))) { os = "WinDriver"; } else { os = "Driver"; } } }