[JavaSE] object-oriented

class definition

[Modifier list] class class name { // class body = attribute + method // attribute exists in the form of "member variable" on the code (describe state) // method describes action/behavior } Note:




  1. The list of modifiers can be omitted;
  2. Instantiate object, new class name();
  3. Variables must be declared before they can be accessed. When member variables are not manually assigned, the system assigns them by default.

Construction method

What is a constructor

The construction method is a special method through which the creation of objects and the initialization of instance variables can be completed. In other words: the construction method is used to create an object, and at the same time assign values ​​​​to the properties of the object.

Default no-argument constructor

When a class does not provide any constructor, the system will provide a parameterless constructor by default. (And this constructor is called the default constructor)

Grammatical structure of constructor

[Modifier list] Class name (formal parameter list) { Construction method body Usually assign values ​​to attributes in the construction method body to complete the initialization of attributes. }


Notice:

  1. The modifier list is currently uniformly written: public. Never write public static, singleton mode – private;
  2. The constructor name must be consistent with the class name;
  3. The constructor does not need to specify the return value type, nor can it write void;
  4. Constructors support method overloading.

call constructor

new constructor name (actual parameter list);

encapsulation

The role of packaging

  1. Ensure the security of the internal structure;
  2. Masking is complex, exposing is simple.

From the perspective of code, after the data in a class body is encapsulated, the caller of the code does not need to care about the complicated implementation of the code, and can only access it through a simple entry. In addition, the data with a higher security level in the class body is encapsulated, and external personnel cannot access it at will to ensure data security.

Implement encapsulation

  1. Attribute privatization (modified with the private keyword);
  2. It provides a simple operation entry to the outside world, which can be modified by the set method and read by the get method.

static keyword

  1. The static keywords used are all class-related and class-level;
  2. The static modification used is all accessed by "class name.";
  3. static modified variable: static variable;
  4. Static modified method: static method.

static block

grammatical format

static { java statement; java statement }


execution time

Executed when the class is loaded, before the main method is executed, and only once.

effect

  1. Static code blocks are not so commonly used;
  2. It is a special moment/opportunity given to us java programmers by sun company - class loading timing.

example code block

grammatical format

{ java statement; java statement; java statement; }



execution time

As long as the construction method is executed, the code in the "Example Statement Block" must be automatically executed before the construction method is executed. In fact, this is also a special opportunity prepared by SUN for java programmers, called the object construction opportunity.

static method call instance member

cannot! ! !

  1. Static methods belong to the class, memory is allocated when the class is loaded, and can be accessed directly through the class name. Non-static members belong to the instance object and only exist after the object is instantiated, and need to be accessed through the instance object of the class.
  2. Static members already exist when non-static members of the class do not exist. At this time, calling non-static members that do not exist in memory is an illegal operation.

Note: When a static method accesses members of this class, it only allows access to static members (that is, static member variables and static methods), and does not allow access to instance members (that is, instance member variables and instance methods), while instance methods do not have this restriction.

this keyword

  1. One object one this. this is a variable, a reference. this saves the memory address of the current object, pointing to itself.
  2. this is stored inside the object in the heap memory.
  3. this can only be used in instance methods. Whoever calls this instance method, this is who. Inside the constructor, this points to the current object.
  4. This can be omitted in most cases. In the instance method, or in the construction method, in order to distinguish local variables and instance variables, "this." cannot be omitted.
  5. New syntax: To call another constructor of this class through the current constructor, you can use the following syntax format:
    this (actual parameter list);
    the call of this() can only appear in the first line of the constructor.

super keyword

  1. super can appear in instance methods and constructors;
  2. The syntax of super is: super., super();
  3. super cannot be used in static methods;
  4. super. Can be omitted in most cases;
  5. super. cannot be omitted when distinguishing between local variables and instance variables;
  6. super() can only appear in the first line of the construction method, and call the construction method in the "parent class" through the current construction method. The purpose is: when creating a subclass object, first initialize the characteristics of the parent class.

Notice:

  • this() and super() cannot coexist, they can only appear in the first line of the construction method;
  • When the first line of a construction method has neither this() nor super(), there will be a super() by default;
  • When an attribute with the same name as the parent class appears in the subclass object, super. cannot be omitted in order to access the "parent class feature" in the subclass object;
  • super is not a reference, does not hold a memory address, and does not point to any object. super only represents
    the parent type feature inside the current object. When super is used, it must be followed by "dot", ie super..

Call format:

  • super.property name [access the properties of the parent class]
  • super. method name [method to access the parent class]
  • super (actual parameter) [Call the constructor of the parent class]

inherit

The role of inheritance

  • Basic function: subclass inherits parent class, code can be reused;
  • Main role: Because of the inheritance relationship, there is a later method coverage and polymorphism mechanism.

inherited properties

  1. When class B inherits class A, class A is called superclass, parent class, and base class, and
    class B is called subclass, derived class, and extended class.
    class A{}
    class B extends A{}
  2. Inheritance in java only supports single inheritance, not multiple inheritance. C++ supports multiple
    inheritance
    .
  3. Although multiple inheritance is not supported in java, sometimes it will produce the effect of indirect inheritance,
    for example: class C extends B, class B extends A, that is to say, C directly inherits B,
    but C also indirectly inherits A.
  4. Java stipulates that a subclass inherits from a parent class, except for the construction method that cannot be inherited, the rest can be inherited.
    But private properties cannot be directly accessed in subclasses.
  5. If a class in java does not explicitly inherit any class, it inherits the Object class by default. The Object class is the
    root class (super parent class) provided by the Java language. That is to say, an object is born with
    all the characteristics of the Object type. .
  6. Inheritance also has some disadvantages, such as the problem of high coupling between subclasses and parent classes.

method override

Rewriting occurs at runtime, and the subclass rewrites the implementation process of the access-allowed methods of the parent class.

When to rewrite?

After the subclass inherits the parent class, when the inherited method cannot meet the business needs of the current subclass, the subclass has the right to rewrite the method, and it is necessary to "overwrite the method".

Note: After the subclass performs "method rewriting" on the method inherited from the parent class, when the subclass object calls the method, the rewritten method must be executed.

overridden condition

  1. The two classes must have an inheritance relationship;
  2. The method name and parameter list must be the same;
  3. The return value type of the subclass method should be smaller or equal to the return value type of the parent class method;
  4. The exception range thrown is less than or equal to the parent class;
  5. Access modifier scope greater than or equal to parent class

Notice:

  • The constructor cannot be inherited, so it cannot be overridden;
  • The private/final/staticdecorated method cannot be overridden, but the staticdecorated method can be declared again.

polymorphism

Upward transformation and downward transformation

Upward transformation: child —> parent (upcasting), also known as automatic type conversion: Animal a = new Cat();
Downward transformation: parent —> child (downcasting), also known as forced type conversion: Cat c = (Cat)a;

When is downward transformation required?

It is necessary to call or execute a method specific to a subclass object, and it must be cast down before it can be called.

Downward Transformation Risk

Prone to ClassCastException (type conversion exception)

How to avoid this risk?

instanceofoperator, which can dynamically determine whether the object pointed to by a reference is of a certain type during the running phase of the program.

What is polymorphism?

Multiple forms, multiple states, compile and run have two different states.

  • Static binding at compile time ;
  • Do dynamic binding at runtime .
//编译的时候编译器发现a的类型是Animal,所以编译器会去Animal类中找move()方法
//找到了,绑定,编译通过。但是运行的时候和底层堆内存当中的实际对象有关
Animal a = new Cat();

//真正执行的时候会自动调用“堆内存中真实对象”的相关方法。
a.move();

Typical polymorphic code: parent class references point to subclass objects .

The role of polymorphism in development

Reduce the coupling degree of the program and improve the scalability of the program.

final keyword

final means immutable meaning,

  1. Final modified classes cannot be inherited;
  2. Final modified methods cannot be overridden;
  3. Final modified variables cannot be modified;
  4. Final modified variables must be initialized explicitly, final modified instance variables are generally added with static modification, and static final joint modified variables are called "constants";
  5. A final modified reference can only point to an object, that is to say, the reference cannot be reassigned, but the pointed object can be modified;
  6. The construction method cannot be modified by final;
  7. It will affect the initialization of the Java class: the static constant defined by final will not execute the java class initialization method when called.

static typing, dynamic typing, static binding, dynamic binding

Any reference variable has two types:

  1. Static type, that is, the type that defines the reference variable;
  2. Dynamic type, that is, the type of object that the reference actually points to.

For example, for two classes A and B, there are: A a=new B();Then, the static type that refers to a is A, and the dynamic type is B.

Static binding: Any action that relies on a static type to associate a method with the class it is in is static binding. Because static binding occurs before the program runs, it is also called early binding.

Dynamic binding: All actions that rely on dynamic types to associate a method with the class in which the method resides are dynamic bindings. Because dynamic binding is implemented through RTTI when the program is running, it is also called late binding.

Note: The properties (variables) of classes in java are all statically bound.

Method Overriding, Method Hiding

  1. All member variables (whether static or non-static) are only statically bound;
  2. For static methods, only static binding is performed;
  3. For non-static methods, dynamic binding occurs.

Method hiding: For the two cases of 1 and 2, after the subclass inherits the parent class, the properties and static methods of the parent class are not erased by the subclass, and can be accessed through the corresponding reference. But it cannot be seen explicitly in subclasses, which is called hiding.

Method coverage: In the case of 3, after the subclass inherits the parent class, the non-static method of the parent class is overwritten by the subclass and cannot be accessed through the corresponding reference (unless an object of the parent class is created to call). This situation is called coverage.

Class initialization process

  1. To create an instance of a class, the class needs to be loaded and initialized first – the class where the main method is located needs to be loaded and initialized first;
  2. To initialize a subclass, you need to initialize the parent class first;
  3. A class is initialized by executing the () method – the () method is automatically generated and found in the bytecode byStatic class variables display assignment codeandstatic blockComposition, which of the two executes first, and executes only once.

Instance initialization process

  1. The initialization of the instance is to execute the () method – the () method may have multiple overloads, and there are several () if there are several construction methods;
  2. () methods includeNon-static class instance variables display assignment codenon-static code blockandCorresponding constructor codeComposition, the first two are executed first, and the constructor code is executed last ;
  3. The corresponding () method is called every time an instance is created, because the first line of the constructor of the subclass is super(); so the () method of the parent class is called every time.

abstract class

What is an abstract class?

There are common features between classes and classes, and these common features are extracted to form abstract classes.

What type is an abstract class?

reference data type

definition syntax

[modifier list] abstract class class name {          class body; }

characteristic

  1. Abstract classes cannot be instantiated and objects cannot be created, so abstract classes are used to be inherited by subclasses;
  2. final and abstract cannot be used in combination, these two keywords are opposite, because the class modified by final cannot be inherited;
  3. A subclass of an abstract class can be either an abstract class or a non-abstract class;
  4. Abstract classes cannot be instantiated, but abstract classes have constructors, which are called by subclasses;
  5. There may not be abstract methods in abstract classes, but abstract methods must appear in abstract classes;
  6. A non-abstract class that inherits an abstract class must rewrite, override, and implement the abstract methods in the abstract class.

abstract method

An abstract method means a method without implementation, without a method body.

define format

public abstract void doSome();

features

  • No method body, ending with a semicolon;
  • The list of modifiers has the abstract keyword.

interface

  1. An interface is a "reference data type";
  2. Interfaces are completely abstract;
  3. Interface supports multiple inheritance;
  4. There are only constants + abstract methods in the interface;
  5. All elements in the interface are publicmodified;
  6. The abstract method in the interface public abstractcan be omitted;
  7. The constants in the interface public static finalcan be omitted;
  8. Methods in interfaces cannot have method bodies;
  9. When a non-abstract class implements an interface, all methods in the interface must be implemented;
  10. A class can implement multiple interfaces;
  11. extends and implement can coexist, extends first, implement after;
  12. Using interfaces, polymorphism can be used when writing code (supertype references point to subtype objects).

define format

[modifier list] interface interface name {         constant;         abstract method; }


The role of interfaces in development

Interface-oriented programming can reduce the coupling degree of the program and improve the scalability of the program, which is in line with the OCP development principle. The use of interfaces is inseparable from the polymorphic mechanism. (Interface + polymorphism can reduce coupling)

Interfaces can be decoupled, and any interface has a caller and an implementer. An interface can decouple the caller from the implementer. The caller calls for the interface, and the implementer writes the implementation for the interface.

Classes and Relationships Between Classes

is a(继承):
	凡是能够满足is a的表示“继承关系“
	A extends B

has a(关联):
	凡是能够满足has a关系的表示“关联关系”
	关联关系通常以“属性”的形式存在。
	A{
	      B  b
	}

like a(实现):
	凡是能够满足like a关系的表示“实现关系”
	实现关系通常是:类实现接口。
	A implements B

The difference between abstract class and interface

  1. Abstract classes are semi-abstract and interfaces are fully abstract.

  2. There are constructors in abstract classes, but there are no constructors in interfaces.

  3. Multiple inheritance is supported between interfaces, and only single inheritance between classes.

  4. A class can implement multiple interfaces at the same time, and an abstract class can only inherit from one class.

  5. Only constants and abstract methods are allowed in interfaces.

Guess you like

Origin blog.csdn.net/LogosTR_/article/details/126239073