Object-Oriented Fundamentals——Silicon Valley Study Notes

Object-Oriented Fundamentals——Silicon Valley Study Notes

foreword

Learn the three main lines of object-oriented
1. Java classes and their members: attributes, methods, and constructors
2. Three major characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstractness)
3. Other keywords:
this, super, static, final, abstract, interface, package, import


overview

Object-oriented programming ideas can basically be understood as object-oriented rules. Both process-oriented and object-oriented are a kind of thought. (There is a saying that everything is an object, it depends on your own understanding)

For example: "Put the elephant in the refrigerator"
is process-oriented, emphasizing functionality as the smallest unit, and considering how to do it. (Execution)
1. Open the refrigerator door
2. Lift the elephant and stuff it into the refrigerator
3. Close the refrigerator door

Process-oriented, emphasizing objects with functions, taking class/object as the smallest unit, and considering who will do it (command)

{
    
    
	打开(冰箱){
    
    
		冰箱.开开();
	}
	抬起(大象){
    
    
		大象.进入(冰箱);
	}
	关闭(冰箱){
    
    
		冰箱 .闭合();
		}
}
冰箱{
    
    
	开开(){
    
    }
	闭合(){
    
    }
}
大象{
    
    
	进入(冰箱){
    
    }
}

Programmers transform from process-oriented executors to object-oriented conductors

Ideas and Steps of Object-Oriented Analyzing Problems

1> According to the needs of the problem, select the entity in the real world that the problem is aimed at
1> Find the attributes and functions related to solving the problem from the entity, and these attributes and functions form the class in the concept world.
1> Describe abstract entities in computer language to form the definition of classes in the computer world . That is, with the help of a certain programming language, the class is turned into a data structure that the computer can recognize and process.
1> Instantiate the class into an object in the computer world . Objects are the ultimate tool for problem solving in the computer world.


The two elements of object-oriented (classes and objects)

Explanation:
Class: The description of a class of things is an abstract and conceptual definition Object: It is each individual of this type of transaction that actually exists, so it
also becomes an instance (instance).

(1) The design class is the member of the design class.
The java code world is composed of many classes with different functions.

Different terms for proper nouns

  • attribute = member variable = field = domain, field
  • method = member method = function = method
  • Create an object of the class = instantiate the class = instantiate the class

(2) The use of classes and objects (implementation of object-oriented thinking) (the creation and execution of Leihe objects are divided into three steps) 1. Create classes and design members of classes (mainly in this step) 2. Create objects of classes 3. Call the structure of objects through "object.property" or
"
object.method
"

example
//测试类
public class PersonTest{
    
    
	public static void main(String[] args){
    
    
		//创建Person类对象
		Person p1 = new Person();
		//Scanner scanner = new Scanner();

		//调用对象的结构:属性、方法
		//调用属性:“对象.属性”
		p1.name = "Tom";
		p1.isMale = true;
		System.out.println(p1.name);

		//
		p1.eat();
		p1.sleep();
		p1.talk("Chinese");
	}
}
class Person{
    
    
	//属性
	String name;
	int age = 1;
	boolean isMale;
	
	//方法
	public void eat(){
    
    
		System.out.println("人可以吃饭"); 
	}
	public void sleep(){
    
    
		System.out.println("可以睡觉"); 
	}
	public void talk(String language){
    
    
		System.out.println("汉语"); 
	}
}


(3) If multiple objects of a class are created, each object independently has a set of attributes of the class. (non-static)
means: if we modify the property a of an object, it will not affect the value of another object property a.
Pay the object address saved by the p1 variable to p3, causing p1 and p3 to point to the same object entity in the corresponding space.
When a property of an object is not assigned a value, the property has a default initialization value.

(4) Memory analysis of objects
Memory area: method area, virtual machine stack, local method stack, heap, program counter
Heap: stacking object instances
Stack: refers to the virtual machine stack. Used to store local variables, etc.
Method area: used to store data such as class information, constants, static variables, code compiled by a real-time compiler, etc. that have been loaded by the virtual machine

Person p1=p3;
//这里就不是创建新对象

class structure

Class structure one: the use of attributes in attribute classes

属性(成员变量) vs 局部变量
1、相同点
1.1定义变量的格式: 数据类型 变量名 = 变量值
1.2先声明,后使用
1.3变量都有其对应的作用域
2、不同点:
2.1 在类中升不明的位置不同
属性:直接定义在类的一对{ }内
局部变量:将声明在方法内、方法形参、代码块内、构造器形参、构造器内的变量
2.2关于权限修饰符的不同
属性:可以再声明属性时,指明其权限,使用权限修饰符
常用的权限修饰符:private、public、缺省、protected -->封装性
目前,声明属性时,缺省
局部变量:不可以使用局部变量
2.3默认初始化值得情况
属性:类的属性,根据其类型,都有默认初始化值
整形(byte/short/int/long):0
浮点型(float/double):0.0
字符型(char):0(或‘\u0000’)
布尔型(boolean):false

Reference data type (class, array, interface): null

Local variables: no default initialization value
means: we must assign a value before calling a local variable
In particular: when the formal parameter is called, we can assign a value

2.4 Location loaded in memory
Attribute: Loaded into the heap space (non-static)
Local variables: Loaded into the stack space

example
public class UserTest{
    
    
}
class User{
    
    
	//属性(或成员变量)
	String name;
	public int age;
	boolean isMale;

	public void talk(String language){
    
    //language:形参
		System.out.println("我们使用"+language+"进行交流");
	}
	public void eat(){
    
    
		String food = "烙饼";//局部变量
		System.out.println("北方人喜欢吃:"+food);
	}
}

Class structure 2: declaration and use of methods in method classes

Method: Describe the functions that the class should have
For example: Math class: sqrt()\random()\...
Scanner class: nextXxx()...
Arrays class: sort()\binarySearch()\toString()\equals()\...

1. Example:
public void eat(){}
public void sleep(int hour){} public
String getName(){}
public String getNation(String nation){}
2. Method declaration: permission modifier return value type method name (formal parameter list (optional)) {method body} Note : methods modified by static, final, and abstract will be discussed later 3. Description 3.1 about permission modifiers : The 4 permission modifiers specified by Java: private, public, default, protected --> encapsulation will be discussed later 3.2 Return value type: return value vs no return value 3.2.1 If the method has a return value, the return value type must be specified when the method is declared. At the same time, in the method, you need to use the return keyword to return a variable or constant of the specified type. If the method does not return a value, void is used when the method is declared. Normally, return is not used in methods that do not return a value. But if you use it, you can only "return;" without data, which means to end this method. 3.2.2 Should we define a method with a return value? ① Topic requirements ② Based on experience: Specific analysis of specific problems 3.3 Method name: belongs to the identifier, follow the rules and specifications of the identifier "see the name and know the meaning" 3.4 Formal parameter list: the method can declare 0, 1, or multiple formal parameters 3.4.1 Format: data type 1 formal parameter 1, data type 2 formal parameter 2,...















3.4.2 When we define a method, should we define formal parameters?
① Topic requirements
② Based on experience: Specific analysis of specific issues
3.5 Method body: embodiment of method functions
4. Use of return keyword:
4.1. Scope of use: used in methods
4.2. Function:
① End method
② For methods with return value types, use the "return data" method to return the requested data.
4.3. Points to note: there can be no execution statement after the return keyword.
5. During the use of the method, the properties and methods of the current class can be called. You can call the method again in the method. Methods can no longer be defined within methods.
Special: method A is called again in method A, this method is called a recursive method.

public class CustomerTest{
    
    
	public static void main(String[] args){
    
    
		Customer cust1 = new Customer;
		cust1.eat();//如果eat方法是private的,在外面是无法调用的
	}
}
//客户类
class Customer{
    
    
	//属性(或成员变量)
	String name;
	public int age;
	boolean isMale;

	public void eat(){
    
    
		System.out.println("客户吃饭");
	}
	public void sleep(int hour){
    
    
		System.out.println("休息了"+hour+"小时");
	}
	public String getName(){
    
    
		return name;
		//return后不可声明表达式
	}
	public String getNation(String nation){
    
    
		String info = nation;
		return info;
	}
}

The use of object class

  1. The object class is the root parent class of all Java classes
  2. If the extends keyword is not used to specify its parent class in the class declaration, the default parent class is the java.lang.Object class
  3. The functions (attributes, methods) in the Object class are universal.
The use of the object class toString method:
  1. When we output a reference to an object, we actually call toString() of the current object
  2. Definition of toString() in Object class:
    public String toString() { return getClass().getName() + “@” + Integer.toHexString(hashCode()); }

  3. Classes like String, Date, File, and wrappers have rewritten the toString() method in the Object class.
    Causes the "entity content" information to be returned when the object's toString() is called
  4. Custom classes can also override the toString() method, when this method is called, returns the "entity content" information of the object
== and equals() (interview question)

First, the use of = =
= = operator

  • Can be used in basic data type variables and reference data type variables
  • If the comparison is a basic data type variable, compare whether the data saved by the two variables are equal. (Not necessarily the same type)
    If the comparison is a reference data type variable, compare whether the address values ​​of the two objects are equal, that is, whether the two references point to the same object entity.
    Supplement: When using the = = symbol, you must ensure that the variable types on the left and right sides of the symbol are consistent.
    Second, the use of the equals() method:
  1. is a method, not an operator

  2. Can only be used for reference data types

  3. The definition of equals () in the Object class
    public Boolean equals (Object obj) { return (this == obj); } Explanation: The functions of equals () and == defined in the Object class are the same, comparing whether the address values ​​of the two objects are the same, that is, whether the two references point to the same object


  4. Like String, Date, File, wrapper classes, etc. have rewritten the equals() method in the Object class. After rewriting, the comparison is not whether the addresses of the two references are the same, but whether the "entity content" of the two objects is the same.

  5. Usually, if our custom class uses equals(), it usually compares whether the "entity content" of two objects is the same, then we need to rewrite equals() in the Object class.

Principles for overriding the equals() method

  • Symmetry: If x.equals(y) returns "true", then y.equals(x) should also be "true"
  • Reflexivity: x.equals(x) must be "true"
  • Transitivity: If x.equals(y) returns "true" and y.equals(z) returns "true", then z.equals(x) should also be "true"
  • Consistency: If x.equals(y) returns "true", as long as the contents of x and y remain unchanged, no matter how many times the equals() method is called repeatedly, the return will be "true". In any case, x.equals(null) will always return "false", and null.equals(x) is a null pointer exception. Therefore, before using the equals() method, you must first determine whether the object is empty; x.equals (an object of a different type from x) always returns "false
    "

Use of wrappers

method details

1. Method overloading (load)

1. Definition: In the same class, more than one method with the same name is allowed, as long as their number or types of parameters are different.


"Two identical but different": same class, same method name,
different parameter lists: different number of parameters, different parameter types

2. Example:
sort()/binarySearch() overloaded in the Arrays class
3. Judging whether it is overloaded:
it has nothing to do with the method’s permission modifier, return value type, formal parameter variable name, and method body
4. When calling a method through an object, how to determine a specified method:
method name -> parameter list

Second, the method of variable parameters

1. The new performance of jdk5.0
2. Specific use
2.1 The format of variable number formal parameters: data type... variable name
2.2 When calling the method of variable number formal parameters, the number of incoming formal parameters can be: 0, 1... 2.3 The method of variable number formal parameters is the same as the method name in this class, and the methods with different parameters constitute overloading , cannot
coexist
.
2.5 Variable number formal parameters Among the formal parameters of the method, they must be declared at the end of the formal parameter list.
2.6 Among the parameters of a method with variable number of parameters, at most one variable parameter can be declared.
example

public class MethodArgsTest{
    
    
	public static void main(String[] args){
    
    
	MethodArgsTest test=new MethodArgsTest();
	test.show(12);
	test.show("hello");
	}
	public void show(int i){
    
    
	}
	//下面两个方法都可使用,如果同时出现且均可使用,优先会使用本方法
	public void show(String s){
    
    
		System.out.println("show(String)");
	}
	//
	public void show(String ... strs){
    
    
		System.out.println("show(String ... strs)");
	}

3. The value transfer mechanism of method parameters

About variable assignment
If the variable is a basic data type, the value assigned is the data value stored in the variable.
If the variable is a reference data type, the value assigned is the address value of the data stored in the variable.

Transfer mechanism of method formal parameters: Value transfer 1. Formal parameter
: the parameter in the parentheses declared when the method is defined. Actual parameter: the data actually passed to the formal parameter when the method is called. The address value of the parameter storage data (including the data type of the variable
) . (Equivalent to passing pointers in C language.)


Fourth, the use of recursive methods (understanding)

1. Recursive method: A method calls itself within the body.
2. Method recursion contains an implicit loop, which will repeatedly execute a certain piece of code, but this repeated execution does not require loop control. Recursion must go in a known direction, otherwise this recursion becomes infinite recursion, similar to an infinite loop.

The third structure of the class: the use of constructors (or constructors, constructors)

construct: construction, construction. construction: CCB constructor: constructor
The default permissions of the constructor are the same as the permissions of the class

1. The use of the constructor:

1. Create an object
Create an object of a class: new + constructor
2. Initialize object information

2. Description

1. If there is no explicit class constructor defined, the system will provide a null-parameter constructor by default. 2. The
format of defining the constructor: permission modifier class name (formal parameter list) actual parameter { } 3.
Multiple constructors defined in a class constitute overloading with each other. 4.
Once we explicitly define a class constructor, the system will no longer provide
a default null-parameter constructor.

Summary: The order of property assignment
① Default initialization value
② Explicit initialization
③ Assignment in the constructor //①②③ can only be assigned once

④ Assign values ​​by means of "object.method" or "object.attribute"//④ you can assign more
values


expand

JavaBean

  • Is a reusable component written in the Java language
  • A Java class that meets the following criteria:
    • class is public
    • has a public constructor with no arguments
    • There are attributes, and there are corresponding get and set methods

UML class diagram

1. + means public type, - means private type, # means protected type
2. Method writing:
method type (+, -) method name (parameter name: parameter type): return value type

JVM memory structure

After compiling the source program, generate one or more bytecode files
We use the class loader and interpreter in the JVM to interpret and run the generated bytecode files. It means that the class corresponding to the bytecode file needs to be loaded into memory, which involves memory parsing.

Recommended book: "JVM Specification"

virtual machine stack

It is the stack structure that is usually mentioned. We store local variables in a stack structure.

heap

We load the new structure (for example: array, object) into the space. Supplement: Object properties (non-static) are loaded into the heap space.

method area

Class loading information, constant pool, static domain.


illustrate

1. Understand that everything is an object

1. In the category of Java language, we all encapsulate functions and structures into classes, and call specific functional structures through instantiation of classes.

  • Scanner,String等
  • File: File
  • Network address: URL

2. When it comes to the interaction between the Java language and the front-end Html and the back-end database, when the front-end and back-end structures interact at the Java level, they are all reflected in classes and objects.

2. Description of memory analysis

Variables of reference type can only store two types of values: null or address value (including the type of variable)

3. Use of anonymous objects

1. Understanding: The object we created is not explicitly assigned a variable name. is an anonymous object.
2. Features: Anonymous objects can only be called once.
3. Use: How to use it in development, you can directly use the anonymous object as a formal parameter. For example p1.send(new mail);

object-oriented features

Object-oriented feature one: encapsulation and hiding

Program design requirements: as high cohesion and low coupling as possible

High cohesion: The internal data operation details of the class are completed by itself, and no external interference is allowed.
Low coupling: Only a small number of methods are exposed to the outside world for use.
Hide the internal complexity of the object and only expose a simple interface to the outside world. It is convenient for external calls. Thereby improving the scalability and maintainability of the system. In layman's terms, hide what should be hidden and expose what should be exposed. This is the design idea of ​​encapsulation.

1. Problem introduction

When we create an object of a class, we can assign values ​​to the properties of the object through the method of "object.property". Here, the assignment operation is restricted by the data type and storage range of the attribute. Other than that, there are no other restrictions. But in practical problems, we often need to add additional constraints to attribute assignment. This condition cannot be reflected in the attribute declaration, we can only add restrictions through methods.
At the same time, we need to prevent users from assigning values ​​to attributes in the way of "object.attribute". Then you need to set the attribute life as private (private)

  • At this time, the encapsulation is reflected for the attributes

Second, the embodiment of encapsulation:

(Not equal to encapsulation, this is just one of the manifestations)
We privatize (private) the attribute Xxx of the class, and at the same time, provide public (public) methods to get (getXxx) and set (setXxx) the value of this attribute

expand
The embodiment of encapsulation:
①As above ②A private method that is not exposed to the outside world. ③ Singleton mode ④ If you don't want the class to be called outside the package, you can set the class as the default

Third, the embodiment of encapsulation requires the cooperation of permission modifiers.

1. The 4 kinds of permissions stipulated by java (arranged from small to large): private, default, protected, public 2. The
4 kinds of permissions can be used to modify the internal structure of the class and the class:
attributes, methods, constructors, and internal classes.

Modifiers can only be used
default, public

Summary of encapsulation: Java provides 4 permission modifiers to modify the internal structure of the class and the class, reflecting the visibility of the class and the internal structure of the class when it is called.

Object-oriented feature two: inheritance

The benefits of inheritance

  1. Reduced code redundancy and improved code reusability
  2. Easy to expand functions
  3. Provides a prerequisite for the use of polymorphism in the future

Inheritance format: class A extends B{}

  • A: subclass, derived class, subclass
  • B: parent class, super class, base class, superclass

2.1 Embodiment: Once the subclass A inherits the parent class B, the subclass A obtains all the properties and methods declared in the parent class B

  • In particular, for attributes or methods whose life is private in the parent class, after the subclass inherits the parent class, it still thinks that it has obtained the private structure in the parent class. It is only because of the impact of encapsulation that the subclass cannot directly call the structure of the parent class.
    2.2 After the subclass inherits the parent class, it can also declare its own unique properties or methods to realize the expansion of functions.
    The relationship between subclasses and parent classes is different from the relationship between subsets and collections.
    extends: extension, expansion

Third, the provisions on inheritance in Java

  1. A class can be inherited by multiple subclasses
  2. Single inheritance of classes in Java: a class can only have one parent class
  3. Child parent class is a relative concept.
  4. The parent class directly inherited by the subclass is called: the direct parent class. The parent class of indirect inheritance is called: indirect parent class
  5. After the subclass inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes.

Four,

  1. If we do not explicitly declare a class's parent class, then this class inherits from the java.lang.Object class
  2. All java classes (except the java.lang.Object class) are directly or indirectly inherited from the java.lang.Object class
  3. Means, all java classes have the functions declared by java.lang.Object class

Five, method rewriting

override/overwrite

  1. Override: After the subclass inherits the parent class, it can override the method with the same name and the same parameters in the parent class
  2. Application: After rewriting, when a subclass object is created and a method with the same name and parameters in the subclass is called through the subclass object, the subclass overrides the method of the parent class when it is actually executed.
  3. Rewriting rules:
    method declaration: permission modifier return value type method name (formal parameter list) { //method body } The convention is commonly known as: the overridden method is called in the subclass, and the overridden method is called in the parent class. ①The method name and formal parameter list of the method overridden by the subclass are the same as the method name and formal parameter list of the overridden method of the parent class. ②The permission modifier of the method overridden by the subclass is not less than the permission modifier of the overridden method of the parent class.




  • Special case: subclasses cannot rewrite methods declared as private permissions in the parent class (because subclasses cannot see them, they will be considered as new methods after rewriting) ③Return value
    type:
  • The return value type of the overridden method of the parent class is void, and the return value type of the method overridden by the subclass can only be void
  • The return value type of the overridden method of the parent class is A type, and the return value type of the method overridden by the subclass can be A class or a subclass of A class
  • The return value type of the overridden method of the parent class is a basic data type (for example: double), and the return value type of the method overridden by the subclass must be the same basic data type (for example: must also be double).
    ④ The exception type thrown by the method rewritten by the subclass is not greater than the exception type thrown by the overridden method of the parent class. (See the exception handling section for details)
illustrate
The methods with the same name and parameters in the subclass and parent class are either declared as non-static (consider rewriting), or both are declared as static (not rewriting) (static methods cannot be overridden)

Object-oriented feature three: polymorphism

  1. Understand polymorphism: It can be understood as multiple forms of a transaction.

  2. What is polymorphism:
    polymorphism of objects: the reference of the parent class points to the object of the subclass (or the reference of the object of the subclass assigned to the parent class)

  3. Use of polymorphism: virtual method calls.
    With object polymorphism, we can only call the method declared in the parent class during compilation, but at runtime, what we actually execute is that the subclass rewrites the method of the parent class.
    Summary: Compile to the left; run to the right.

  4. Prerequisites for the use of polymorphism: ① class inheritance relationship; ② method rewriting

  5. The polymorphism of objects is only applicable to methods, not to attributes (see left for compilation and operation)

  6. If the subclass rewrites the method of the parent class, it means that the method defined in the subclass completely covers the method of the same name in the parent class, and the system will not be able to transfer the method in the parent class to the subclass. Compile to see the left, run to see the right.

  7. For instance variables, this phenomenon does not exist. Even if the instance variables in the subclass are exactly the same as those in the parent class, it is still impossible for this variable to overwrite the instance variables defined in the parent class. Compilation and operation are all on the left.

Summary
Virtual method calls (in the case of polymorphism)
subclasses define methods with the same name and parameters as the parent class. In most cases, the method of the parent class at this time becomes a virtual method, and the parent class dynamically calls the method belonging to the subclass according to the different subclass objects assigned to it. Such method calls cannot be determined at compile time.

Compile-time type and runtime type
The compile-time object is the parent class, and the method call is determined at runtime, so the rewritten method of the subclass is called – dynamic binding

The polymorphic parent class cannot call the method properties unique to the subclass;
with the polymorphism of the object, the subclass-specific properties and methods are actually loaded in the memory, but because the variable is declared as the parent class type, when compiling, only the properties and methods declared in the parent class can be called, and the properties and methods specific to the subclass cannot be called.
How can I call subclass-specific properties and methods?
For downcasting, use the mandatory type conversion operator.

When using strong cast, the exception of ClassCastException may appear.

The use of the instanceof keyword
a instanceof A: Determine whether the object a is an instance of class A. If yes, return true; if not, return false

Usage scenario: In order to avoid ClassCastException during downcasting, we first perform instanceof judgment before downcasting, and once it returns true, downcasting is performed. If false is returned, no downcast is performed.

If a instanceof A returns true, then a instanceof B also returns true. (Among them, class B is the parent class of A.)

Interview questions
Method overloading and rewriting
1. Definition details
Overloading: The constructor can also be overloaded
Method rewriting: After the subclass inherits the parent class, it can override the method in the parent class
2. From the perspective of compilation and operation:
Overloading means that multiple methods with the same name are allowed, and the parameters of these methods are different. During compilation, the name of the method with the same name is modified according to the different parameter lists of the method. To the compiler, these methods with the same name are different methods. Their call addresses are bound at compile time. Java's overloading can include parent classes and subclasses, that is, subclasses can overload methods with the same name and different parameters of the parent class.
So for overloading, before the method is called, the method to be called has been determined at the compilation stage, which is called "early binding" or " static binding" . To quote Bruce Eckel "Don't be stupid, if he is not late binding, he is not polymorphic" 3. Overloading does not represent polymorphism, rewriting represents polymorphism.



keywords

Keyword: use of this

1. this can be used to modify and call: properties, methods; constructors
2. The method of this modifying properties:

this understood as
the current object or an object currently being created
  • Among the methods of the class, we can use "this.property" or "this.method" to call the current object property or method. However, under normal circumstances, we all choose to omit this. In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use the "this. variable" method to indicate that the variable is an attribute, not a formal parameter.
  • Among the methods of the class, we can use "this.property" or "this.method" to call the object property or method currently being created. However, under normal circumstances, we all choose to omit this. In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use the "this. variable" method to indicate that the variable is an attribute, not a formal parameter.
    3. this calls the constructor
  • ①In the constructor of the class, we can explicitly use this (formal parameter list) method to call other constructors specified in this class
  • ②The constructor cannot call itself through this (formal parameter list)
  • ③ If there are n constructors in a class, at most n-1 constructors use this (parameter list)
  • ④ stipulates that this (formal parameter list) must live in the first line of the current constructor
  • ⑤ Inside the constructor, at most one this (parameter list) can be declared to call other constructors

Use of the super keyword

  1. Super is understood as: the parent class
  2. super can be used to call: properties, methods, constructors
  3. use of super
  • 3.1 We can use "super. property" or "super. method" in the method or constructor of the subclass to explicitly call the property or method of life in the parent class. But usually, we are used to omit "super."
  • 3.2 Special case: When the attribute with the same name is defined in the subclass and the parent class, if we want to call the attribute declared by the parent class in the subclass, we must explicitly use the "super. attribute" method to indicate that the attribute declared in the parent class is called.
  • 3.3 Special case: When the subclass rewrites the method in the parent class, when we want to call the overridden method in the parent class in the method of the subclass, we must explicitly use the "super. method" method to indicate that the method declared in the parent class is called.
  1. super calls the constructor
  • 4.1 We can explicitly use the "super (parameter list)" method in the constructor of the subclass to call the specified constructor declared in the parent class
  • 4.2 The use of "super (formal parameter list)" must be declared on the first line of the subclass constructor!
  • 4.3 In the class constructor, we can only choose one of "this (formal parameter list)" or "super (formal parameter list)", and cannot appear at the same time.
  • 4.4 In the first line of the constructor, there is no explicit declaration of "this (parameter list)" or "super (parameter list)"
  • 4.5 Among the multiple constructors of the class, at least one of the constructors of the class uses "super (formal parameter list)" to call the constructor in the parent class

The whole process of subclass object instantiation

  1. From the result point of view: (inheritance)
    After the subclass inherits the parent class, it obtains the attributes or methods declared in the parent class
    to create the object of the subclass, and in the heap space, all the attributes of life in the parent class will be loaded.
  2. From the process point of view:
    when we create a subclass object through the constructor of the subclass, we must directly or indirectly call the constructor of the parent class, and then call the constructor of the parent class of the parent class until we call the constructor of the empty parameter in the java.lang.Object class. Just because all parent class structures have been loaded, you can see that there are parent class structures in memory, and subclass objects can be considered for calling.

Clear: Although the constructor of the parent class is called when the subclass object is created, an object has been created from beginning to end, which is the subclass object of new.

Keywords: the use of package and import

1. Use of the package keyword

  1. In order to better realize the management of classes in the project, the concept of package is provided
  2. Use package to declare the package to which the class or interface belongs, and declare it in the first line of the source file
  3. Packages, belonging to identifiers, follow the naming rules of identifiers, specifications (xxxyyyzzz), "see the name and know the meaning"
  4. Every time "." represents a layer of file directory.
    Supplement: Under the same package, interfaces and classes with the same name cannot be named.
    Interfaces and classes with the same name can be named under different packages.

Expansion: MVC design pattern
One of the commonly used design patterns in MVC, the whole program is divided into three levels: (V) view model layer, (C) controller layer, (M) data model layer. This design pattern, which separates program input and output, data processing, and data display, makes the program structure flexible and clear. It also describes the communication method between various objects of the program, reducing the coupling of the program.

Second, the use of the import keyword

import : import

  1. In the source file, explicitly use the import structure to import the classes and interfaces under the specified package.
  2. declared between the declaration of the package and the declaration of the class
  3. If you need to import a pair of structures, you can write them side by side
  4. You can use the "xxx.*" method, which means you can import all structures under the xxx package
  5. If the class or interface used is defined under the Java.lang package, the import structure can be omitted
  6. If the class or interface used is defined under this package, the import structure can be omitted
  7. If in the source file, a class with the same name that is not under the package is used, at least one class must be displayed with the full class name
  8. If "xxx.*" is used, it means that all structures under the xxx package can be called. But if you are using the structure under the xxx subpackage, you still need to explicitly import the subpackage
  9. import static : imports static structures: properties or methods in the specified class or interface.

# Test the JUnit unit test steps in java: 1. Select the current project -- right-click to select: bulid path --add libraries --JUnit4 -- Next step 2. Create a Java class for unit testing. The Java class requirements at this time: ① This class is public ② This class provides a public no-argument constructor

The use of the static keyword
1. static: static
2. static can be used to modify: properties, methods, code blocks, internal classes
3. Use static to modify properties: static variables
3.1 properties: according to whether to use static modification: divided into: static properties VS non-static properties (instance variables)
Instance variables: We have created multiple objects of the class, and each object independently has a set of non-static properties in the class. When modifying a non-static property of one of the objects, it will not cause the same property value to be modified in other objects.
Static variable: multiple objects of the class we created, multiple objects share the same static variable. When a static variable is modified through an object, it will cause other objects to call this static variable, which is modified.
3.2 Other descriptions of static modified attributes:
①Static variables are loaded with the loading of the class. It can be called through the method of "class. static variable"
②The loading of static variables is earlier than the creation of objects.
③ Since the class will only be loaded once, there will only be one copy of the static variable in the memory: the existing method obtains the static field.
④ Classes cannot call instance variables.

class variable instance variable
kind yes no
object yes yes

3.3 Examples of static properties: System.out; Math.PI;

4. Use static to modify the method: static method
① is loaded with the loading of the class, and can be called by "class.method"

static method non-static method
kind yes no
object yes yes

③ Only static methods or properties can be called in static methods. (Consistent life cycle)
In non-static methods, non-static methods or properties can be called, and static methods or properties can also be called.
5. Static Notes:
5.1 In static methods, the this keyword and the super keyword cannot be used.
5.2 Regarding the use of static properties and static methods, everyone understands it from the perspective of life cycle.

6. During development, how to determine whether an attribute should be declared as static?
/> The method of manipulating static properties, usually set as static
The method in the /> tool class is customarily declared as static, such as: Math, Arrays, Collections

software use

eclipse shortcut keys

  1. Completion code: alt + /
  2. Quick fix: ctrl+1
  3. Batch import package: ctrl + shift + o
  4. Use single-line comments: ctrl + /
  5. Use multi-line comments: ctrl + shift + /
  6. Uncomment multiple lines: ctrl + shift + \
  7. Copy the specified code: ctrl + alt +down or ctrl + alt + up
  8. Delete the specified code: ctrl + d
  9. Move code up and down: alt + up or alt + down
  10. Switch to the next line of code: shift + enter
  11. Switch to the previous line of code: ctrl+shift+enter
  12. How to view the source code: ctrl + select the specified structure or ctrl+shift +t
  13. Return to the previous edited page: alt + left
  14. Go to the next edit page (for 13 items): alt + right
  15. Select the specified class with the cursor to view the inheritance tree structure: ctrl + t
  16. Copy code: ctrl+c
  17. Undo: ctrl + z
  18. Undo: ctrl + y
  19. cut: ctrl + x
  20. Paste: ctrl + v
  21. Save: ctrl + s
  22. Select all: ctrl + a
  23. Format code: ctrl + shift + f
  24. Select several lines and move backward as a whole: tab
  25. Select several lines and move forward as a whole: shift + tab
  26. In the current class, display the class structure, and support searching for specified method attributes, etc.: ctrl + o
  27. Modify the specified variable name, method name, class name, etc. in batches: alt + shift + r
  28. Switch the case of the selected structure to uppercase: ctrl + shift + x
  29. Switch the case of the selected structure to lowercase: ctrl + shift + y
  30. Call out structures such as getter/setter/constructor: alt + shift + s
  31. Display the properties of the currently selected resource (project or file): alt + enter
  32. Quick Find: ctrl + k
  33. Close the current window: ctrl + w
  34. Close all windows: ctrl + shift + w
  35. View where the specified structure has been used: ctrl + alt + g
  36. Find and replace: ctrl + f
  37. Maximize the current View: ctrl + m (double-click is also available)
  38. Position directly to the first position of the current line: home
  39. Go directly to the end of the current line: end

The use of eclipse debug

How to debug the program:
1. Add the input statement. System.out.println();
2. Eclipse Debug

  1. Set a breakpoint (double click)
  2. step over Skip (f6) execute the statement of the current line and enter the next line
  3. step into jump into (f5) into the currently called method
  4. drop to frame returns to the first line of the method where the current line is located
  5. step return (f7) points to the method where you dig your current line, go to the next line
  6. resume resumes executing all the code at the breakpoint where the current line is located, enters the next breakpoint, and ends if there is no
  7. Terminate terminates and stops the JVM, and subsequent programs will not be executed.

Guess you like

Origin blog.csdn.net/G_Shengn/article/details/123065477