"Java Core Technology" Reading Notes (1)-Object Oriented, Inner Class, Lambda Foundation

Basic programming structure

Every Java application must have a main method

object.method(parameters)

Comment

  • Single line ///
  • Long story / * * /
  • Automatically generate documents / ** * /

Basic data type (primitive type)

Strong typing: You must declare a type for each variable

  1. Integer
    byte
    short
    int
    long

  2. Floating-point
    float
    double
    (positive infinity, negative infinity, NaN)

  3. char (2byte)
    Unicode characters are represented by one or two char types.
    Use char to describe all Unicode characters: code points (17 code levels)

  4. boolean
    integer and boolean cannot be converted

Variables and operations

  1. Variable
    declaration (named)
    initialization

  2. Constant
    final: can only be assigned once
    Class constant: used in multiple methods of a class (static final)

  3. Operators
    Add, subtract, multiply, divide (result difference when dividing by zero), modulo
    Floating point operation, maintain the accuracy at the time of transplantation, use strictfp to modify the class or method (truncate operation, may overflow)

    • Math
      routines in the floating-point unit of the computer, to get the same result on multiple platforms, use StrictMath

    • Type conversion
      Basic type conversion
      imaginary arrow: conversion with loss of precision In
      binary operations, the operands are converted to the same type before the operation:

      1. If one of the operands is double, the other is converted to double
      2. 。。。。。。。。。。float,。。。。。。。float
      3. 。。。。。。。。。。long,。。。。。。。。long
      4. Otherwise, both operands will be converted to int
    • Combining assignment and operator
      + =-= * = / = (when the last variable is different from the calculation result type, a forced conversion is triggered)
      increment and decrement

    • Relational and boolean operators

    • Bitwise operator
      XOR XOR

    • Brackets and operator rules

    • enumerate

  4. String
    subString
    format
    is immutable: efficiency trade-off-string constant sharing

    CodePoint: One or two code units (char)

  5. input Output

    • Input
      Scanner: Associate standard input System.in, scanner.nextLine, next (), netInt ()
      Console: read password from the console cons.readPassword ("Password:")

    • 输出
      System.out.printf("%8.2f", x);
      System.out.printf(“Hello, %s. Next year, you’ll be %d”, name, age);
      Conversion characters for printf
      Format specifier syntax

    • File IO
      read: Scanner in = new Scanner (Paths.get ("myfile.txt"), "UTF-8");
      write: PrintWriter out = new PrintWriter ('myfile.txt "," UTF-8 " );
      Determine the startup path: String dir = System.getProperty ('user.dir "):

  6. Control flow

    • Block scope

    • Conditional statements

    • Loop
      while: execute only while true
      : execute first and then judge, execute at least once
      for

    • Multi-select switch statement
      case labels can be: byte, short, int, char, enumeration variables, string literals, pay attention to case penetration issues

    • Interrupt control flow

      • continue

      • Labeled break-jump out of multiple nested controls

        label:
        {
            // deal with bad situation
            // carry out normal processing
            if (condition) break label; // exits block
            ... 
        }
        
        // jumps here when the break statement executes
        

Objects and classes

class

Relationship between classes

  1. rely
  2. Related (know, understand)
  3. Aggregate (own)
  4. inherit

static

  1. Static domains,
    also called class domains, belong to classes, and objects that do not belong to any class. In the instance domain, every object has its copy.
    Initialization: Specify the initialization value at the time of declaration, static initialization block initialization

    // static initialization block
    static
    {
        Random generator = new Random();
        nextld = generator.nextlnt(1OOOO);
    }
    

  2. Examples of static final fields (static constants) : Math.PI, System.out (setOut native method)

  3. Static method

    Features:

    • No implicit parameters
    • Can access static domains
    • Callable via object (easy to confuse)

    scenes to be used:

    • The method to complete the execution only through the display parameters (methods that do not require access to the state of the object)
    • Just access the method of the class static domain
    • FactoryMethod constructs objects to
      solve the constructor problem: unable to name and change the construction type (the returned object is a subclass object)
    • main method (can be used for unit testing)

Object

Three characteristics of objects: behavior, state, identification

Domain (object domain or instance domain)

statement

  1. private (pulic destroys encapsulation)
  2. Optional final modification (mostly applied to the basic type primitive, immutable immutable class)

Benefits of encapsulation (provide domain accessor, domain changer method mutator method, accessor method)

  1. Can change the internal implementation, only affect the code of this class
  2. Changer method can perform error checking

Accessor

  1. Don't write accessor methods that return mutable objects. To return, clone first
  2. Each method in the class will not change its object, this class is immutable
  3. C ++ note: const modified accessor method

initialization

  1. Set the value in the constructor (initialize the default value when creating the class-different from local variables)
  2. Assignment in life
  3. Initialization block (initialization block, executed before the constructor is executed)

method

  • Internal: access to the domain
    class method can access the private domain of any object of the class

    public boolean equals(Employee other)
    {
        return name.equals(other.name);
    }
    
  • External: method call

    • Method signature: method name, parameter type; return type does not belong to method signature
    • Overload: Same method name, different parameters
    • Overload resolution (compilation phase)

parameter

  • Types of:

    • Implicit (implicit), explicit (explicit)
      (this: call the object domain, constructor)
    • Basic data types, object references
  • Pass by value: Whether it is a primitive type or a reference type variable, the value will be copied

    • Method cannot modify basic data type parameters
    • Can change the state of object parameters
    • Object parameters cannot refer to new objects

package

import class, static domain, static method

Inheritance

The meaning of polymorphism The
use of enumeration class
What is reflection?

Object basic methods

equals

rule:

  1. Reflexivity
  2. symmetry
  3. Transitivity
  4. consistency
  5. For any non-null reference, x.equals (null) returns false

achieve:

  1. The parameter is named otherObject, which is converted to other variable
  2. Check if this and otherObject refer to the same object
  3. whether otherObject is null
  4. Whether this and otherObject belong to the same class
    • Subclasses have their own concept of equality, using getClass
    • The superclass determines the concept of equality, using instanceOf
  5. Convert otherObject to corresponding class type variable
  6. Compare the required fields, the object field is used
    • Objects.equals comparison, basic type field ==
    • If equals is redefined in a subclass, it is necessary to include super.equals (other)

hashCode

achieve:

  1. Objects.hashCode ()-returns 0 if the parameter is null
  2. Double.hashCode ()-Avoid creating Double objects
  3. Objects.hash (……)-call hashCode method on parameters and combine

  1. getClass().getName + “[attrName:value,……]”
  2. Arrays.toString 、Arrays.deepToString

reflection

Programs that can analyze class capabilities are called reflective

effect:

  1. Run-time analysis capabilities
  2. View objects at runtime
  3. Implement common operations (example: common array expansion)

Class

Save type information at runtime

  1. Get Class object

    • Object.getClass()
    • Class.forName ()-can be used to provide a loading page when the program starts
    • Type.class --示例:Class cl = int.class;

    One class object for each type: e.getClass () == Employee.class

  2. Create class object

    • clzz.newInstance () calls the default constructor, or throws an exception if there is no default constructor
    • constructor.newInstance()

Analysis

Get domain, method:

  1. getFields, getMethods, getConstructors Get public members of classes and their superclasses
  2. getDeclareFields, getDeclareMethods, getDeclareConstructors get all members (excluding superclass members)

Field

  1. Get the value
    f.get (obj)-security manager control, private domain access needs to override the access control
    f.getDouble (obj)

  2. Set value
    f.set (obj, value)
    AccessibleObject.setAccessible (true)

Method

clazz.getMethod (name, Class… parameterTypes)
m.invoke (obj, Object…)-no implicit parameters, obj is null

Constructor

Public methods:

  1. getName
  2. getModifiers (can be analyzed by Modifie static method, toString method can print modifiers)
  3. setAccessible(true)

Generic array expansion (application)

Arrays.copyOf

Problem: new Object [newLength]
-can't directly expand the array, you need to create a new array of the same type as the original solution: Array.newInstance ()

Class.getComponentType()
Array.getLength(a)
System.arraycopy()

Inherit design skills

  1. Public operations and classes are placed in superclasses
  2. Don't use protected domains (don't set the domain to protected—the collection of subclasses will limit the encapsulation, and the same package class can also be accessed)
  3. Use inheritance to achieve is-a relationship
  4. Do not use inheritance unless all inherited methods are meaningful
  5. When overriding methods, do not change the expected behavior
  6. Use polymorphism instead of type information
  7. Don't use reflection too much.

interface

concept

An interface is not a class, but a set of requirements describing the class. These classes must be defined in accordance with the unified format of the interface description

The class implements the interface: the implementation method is specified as public, otherwise the package visibility

Note: The anti-symmetric rule in the case of inheritance
throws a ClassCastException when violated:

  1. If the comparison between subclasses means different things, it is illegal to compare objects of different classes. Each compareTo method should perform the following tests at the beginning:
    if (getClass ()! = Other.getClass ()) thrownewClassCastException ()
  2. If there is such a general algorithm that can compare two different subclass objects, you should provide a compareTo method in the superclass and declare this method as final

characteristic

  • Not instantiable, but interface type variables can be defined and can be detected by instanceOf
  • Can be expanded
  • May contain constants, default push static final
  • A class can implement multiple interfaces
  • The default method provides a default implementation for the interface method and can call other methods (Usage: Interface Evolution)

Note: The conflict resolution of the default method?

  1. Superclass first (compatible with JavaSE7)
  2. Interface conflicts need to be covered

Contrast abstract class

Think of an interface as an abstract class with no instance domain

There is an abstract class and an interface is also needed: each class can only be extended in one class.
Interfaces can provide most of the benefits of multiple inheritance, while also avoiding the complexity and inefficiency of multiple inheritance.

Interface example

  1. callback mechanism: indicates the action that should be taken when a specific event occurs

  2. Comparator
    Arrays.sort

  3. Cloneable

    If you want copy to be a new object, its initial state is the same as the original, but then they will each have their own different state, in this case, you can use the clone method

    The default clone operation is "shallow copy". When the cloned object and the original object share sub-objects as variable objects, calling the changer method will tamper with the state of another object, causing inconsistencies.

    1. Whether the default clone method meets the requirements;
    2. Is it possible to call clone on mutable sub-objects to patch the default clone method;
    3. Whether to use clone (default)

    The Cloneable interface serves only as a marker to instruct class designers to understand the cloning process

The tag interface does not contain any methods; its sole purpose is to allow the use of instanceof in type queries

Lambda expression

concept

It is a transferable code block that can be executed one or more times in the future.

Before: Passing a code segment in Java is not easy, you cannot directly pass the code segment. Java is an object-oriented language, so an object must be constructed. The class of this object needs to have a method that can contain the required code.

grammar

(Parameter)-> expression

  • Parameter types can be ignored if they can be derived
  • There is only one parameter, and the type can be deduced, the parentheses can be ignored
  • No need to return type, derived from the context

application

For an interface with only one abstract method, when an object of this interface is needed, a lambda expression can be provided. This interface is called a functional interface

Method reference

There may already be a ready-made method to complete an action you want to pass to other code

  • object::instanceMethod
  • Class::staticMethod
  • Class :: instanceMethod (the first parameter is called the method target)
    can use this and super parameters
Constructor reference

Method reference with method name new

You can use the array type to establish a constructor reference. As int [] :: new

Java has a limitation: it is not possible to construct an array of generic type T, which can be solved using the array constructor:
Person [] people = stream.toArray (Person [] :: new);

Variable scope

The lambda expression has 3 parts:

  1. Method body
  2. parameter
  3. The value of a free variable
    refers to a variable (captured by a lambda) that is not a parameter and is not defined in the code
    : the lambda is converted to an object containing a method, and the value of the free variable is copied into the instance variable.
    (Closure): A special function that references external scope variables

Rule: The variable captured in the lambda expression must actually be the final variable
(effectively final: this variable will not be assigned a new value after it is initialized)
. The value is changed in the lambda, and the concurrency situation is not safe. Changes outside are also not allowed.

This keyword refers to the this parameter that creates this lambda expression method

Processing lambda

Lambda is used for: deferred execution

  • Run the code in a separate thread;
  • Run the code multiple times;
  • Run the code in the appropriate place of the algorithm (for example, comparison operations in sorting
  • Execute code when something happens (eg, click a button, data arrives, etc.)
  • Only run code when necessary.

Choose or provide a functional interface, the common table is as follows:
Commonly used functional interfaces
Basic type functional interface

Inner class

inner class: Class For defined in a class
For:

  • Internal class methods can access data in the scope of the class definition, including private data;
  • Internal classes can be hidden from other classes in the same package;
  • When you want to define a callback function and do not want to write a lot of code, it is convenient to use anonymous inner classes.

use

  • The object of the inner class always has an implicit reference, which points to the object of the outer class that created it
  • The inner class can access both its own data domain and the data domain of the peripheral class object that created it
  • Only inner classes can be declared private, so only outer classes can construct inner class objects.

Special syntax rules
Reference outer class expression: OuterClass.this.beep
inner class constructor outerObject.new InnerClass (construction parameters)
Reference class outside the scope of the outer class: OuterClass.InnerClass

All static fields declared in the inner class must be final. The
inner class cannot have static methods. The Java language specification does not explain this limitation. You can also allow static methods, but only access static fields and methods of peripheral classes

principle

Internal classes are a compiler phenomenon, and the virtual machine knows nothing about it. The compiler generates a constructor with external class parameters for the internal class, and provides a static method to access the state of the external class object

Reflection decompilation parsing bytecode
java reflection.ReflectionTest irmerClass.lil kingClock \ STimePrinter
or
javap -private ClassName

You can create a class under the same package and use the virtual machine to specify private variables that are accessed by internal classes, undermining security.

Local inner class

Local classes defined in methods cannot be declared with public or private access specifiers. Its scope is limited to the block that declares this local class.
Advantages:

  1. Can be completely hidden from the outside world
  2. Not only can access the external classes that contain them, but also local variables. However, those local variables must actually be final (sometimes the final restriction is not convenient, you can use an array of elements instead of parameters)

Anonymous inner class

If you only create an object of a local inner class, you do not need to name it. This class is called anonymous inner class

new SuperType(construction parameters) {
inner class methods and data
}

Anonymous classes cannot have constructors. Instead, they pass constructor parameters to the superclass.
There can be no construction parameters when implementing an interface.

Application skills:

  • "Double bracket initial invite" (new ArrayList () {{add ("Harry"); add ("Tony");}});
  • Static method generates class name information new Object () {}. GetCIass (). GetEndosingClass0 // gets class of static method

Note: When implementing the equals method, the test for the anonymous subclass getClass will fail;

Static inner class

When using an inner class just to hide a class inside another class, there is no need for the inner class to refer to the outer class object. To this end, you can declare the inner class as static, in order to cancel the generated reference.

  • Unlike regular inner classes, static inner classes can have static fields and methods
  • Inner classes declared in the interface automatically become static and public classes.
    Only inner classes can be declared static

proxy

For: Using a proxy, you can create a new class that implements a given set of interfaces at runtime, and is used to:

  • Route method call to remote server
  • Correlate user interface events and actions during program execution
  • For debugging, trace method calls

The created class has the following methods:

  • Specify all the methods required for the interface;
  • All methods in the Object class.

Provide an invocation handler

use

Create proxy object: Proxy's newProxyInstance method, parameters include

  • class loader, null means the default class loader;
  • An array of class objects, interfaces to be implemented by the elements;
  • Call processor

characteristic

  • Proxy classes are created during program operation, all proxy classes extend the Proxy class, and a proxy class has only one instance domain-call processor
  • All proxy classes override the methods toString, equals and hashCode in the Object class
  • For a specific class loader and a preset set of interfaces, there can be only one proxy class (this class can be obtained using the getProxyClass method)
  • The proxy class must be public and final.
  • Proxy.isProxyClass detects whether a particular Class is a proxy class

summary

So far, the basic concepts of the Java programming language have been sorted out. Including Java-based object-oriented basics, interface-related knowledge, as well as internal classes, Java 8 new Lambda expressions, etc.

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/104559070