[untitled] JavaSE learning experience

Posted by Tubby on Mon, 03 Jan 2022 23:09:54 +0100

Words written at the beginning

After the end of the postgraduate entrance examination in 2021, I feel that time has passed quickly. The postgraduate entrance examination not only brings me systematic learning of basic knowledge, but also teaches me how to learn and think about myself. It also gives me the courage and perseverance to face anything in the future. As long as I want to achieve it, I will not be afraid of difficulties and forge ahead.
Thank the crazy God of station B! He is my mentor on the Java Road. His class is humorous, but very practical. At the same time, he also taught me a lot of experience in life and work. I have always liked such teachers (including Zhang Yu, Liu Xiaoyan, Xu Tao, leg sister, etc. on the way to the postgraduate entrance examination). What they teach you is not only knowledge, but also spiritual resonance. They can feel the personality charm of these teachers, and imperceptibly affect more and more people. In the winter vacation, I intend to re systematically study java, from JavaSE to distributed, and use my blog to record the gains and experiences along the way.
Share a favorite sentence: as long as you are full of hope, you will be invincible!
January 1, 2022

Basic Dos commands

How to open CMD

1. Start + system + command prompt
2. Press Win+R to enter cmd (recommended)

3. Under any folder, hold down the shift key + right click to open the command window here
4. Add cmd path before the address of the resource manager

Run as administrator: get the highest privileges

Common Dos commands

1.E: (enter disk E)
2.dir view all files on the current disk

3. From disk d to disk F, a file (QQLive) can be operated with / D: cd /d F:\QQLive

4. Return to the previous level cd

5. Enter the cd folder name of a folder under this disk (QQLive)

6. Clean the screen cls

7. exit the terminal

8. Check the computer ip ipconfig

9. Turn on computer calc

10. Punch in drawing tool mspaint

11. Punch in notepad

12. ping the website IP information (don't Ctrl+v, right click to paste)

13. Create folder md

14. Create text CD > a.txt
Create document CD > A.docx

15. Delete text (document) del a.docx

16. Delete folder rd test

Generate JavaDoc

1. Use IDEA tool

2. You can use DOS command

The birth of the Java Empire

  • C was born in 1972

    • Close to hardware, very fast operation and high efficiency
    • Operating system, compiler, database, network system, etc
    • Pointer and memory management
  • C + + was born in 1982

    • object-oriented
    • Compatible with C
    • Graphics, games, etc

    resistance

    • We need to create a new language:
      • Grammar like C
      • No pointer
      • No memory management
      • Truly portable, write once, run everywhere
      • object-oriented
      • Type safety
      • High quality internal library
      • . . . . . .

    The birth of Java

    • Java initial
      • The 1995 web page is simple and rough, lacking interactivity
      • Graphical interface program (Applet)
      • Bill Gates said: This is the best language designed so far!
      • Java 2 Standard Edition (J2SE): to occupy the desktop
      • Java 2 mobile terminal (J2ME): to occupy the mobile phone
      • Java 2 Enterprise Edition (J2EE): to occupy the server
    • Java development
      • A great number of platforms, systems and tools have been developed based on Java

        • Build tools: Ant, Maven, Jekins
        • Application server: Tomcat, Jetty, weblogic
        • Web development: Struts, Spring, Hibernate, Mybatis
        • Development tools: Eclipse, IDEA
      • 2006: Hadoop (big data field)``

      • 2008: Android (mobile)

      • Now: three high architecture: in distributed, microservices are often used: high availability, high performance and high concurrency

Java features and benefits

  • Simplicity
  • object-oriented
  • Portability
  • High performance
  • Distributed
  • Dynamics: Reflections
  • Multithreading
  • Security
  • Robustness

JDK,JRE,JVM

Java Foundation

method




Process oriented and object oriented


Creation of classes and objects

Class and object relationships

Create object memory analysis

summary

  1. Classes and objects
    Class is a template: abstract; Object is a concrete instance
  2. method
    Definition, call
  3. Corresponding reference
    Reference type: basic type (8)
    Objects are operated by reference: stack - > heap
  4. Properties: Field member variables
    Default initialization:
    Number: 0.0
    char : u0o00
    booLean:false
    Reference: null
    Modifier attribute type attribute name = attribute value!
  5. Object creation and use
    You must use the new keyword to create objects, constructors
    (Person kuangshen = new Person();)
    Object's property kuangshen name
    Object sleep()
  6. class
    Static properties: properties
    Dynamic behavior: Methods

constructor

Constructors are generally used to assign initial values

Parameterless constructor

package learn;
//Define a Person class
public class Person {
   String name;
}

package learn;

public class way {
    public static void main(String[] args) {
        Person zs = new Person();//After a new three object is created, the parameterless constructor is called by default. The parameterless constructor initially makes the name value NULL
        System.out.println(zs.name);
    }

}


Parametric constructor

Tips, shortcut key generation constructor: alt+inset


encapsulation

  1. The dew that should be exposed, the hide that should be hidden
    Our program design should follow = = "high cohesion, low coupling" = =. High cohesion means that the internal data operation details of the class are completed by ourselves, and external interference is not allowed; Low coupling: only a small number of methods are exposed for external use.
  2. Encapsulation (data hiding)
    Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding.
  3. Remember this sentence: property private, get/set
  4. Tip: alt+insert
package learn;

public class Student {
    //Property is private and can only be called through the get/set method
    private String name;
    private int id;
    private char sex;
    private int age;

    //Provide Public get and set methods
    //get gets the data, and set sets the data
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age>0&&age<120){
            this.age=age;
        }else
          this.age=3;//Three year old
    }
}

package learn;

public class way {
    public static void main(String[] args) {
       Student LiMing=new Student();
       LiMing.setAge(-1);
        System.out.println(LiMing.getAge());
    }

}



Meaning of encapsulation

  1. Improve program security and protect data
  2. Implementation details of hidden code
  3. Unified interface
  4. System maintainability has increased

inherit

package learn;
//Define a parent class
public class Father {

    //public
    //protected
    //default
    //private, subclasses cannot inherit directly
    public String house="villa";
    private int monkey=10_0000_0000;
    public void say(){
        System.out.println("Said a word");
    }
}

package learn;


//If a subclass inherits from the parent class, it inherits all the methods and attributes of the parent class except private
public class Son extends Father{

}

package learn;

public class way {
    public static void main(String[] args) {
        Son son = new Son();
        son.say();
        System.out.println(son.house);
        System.out.println(son.monkey);//Pop red, can't inherit
    }

}

How does private work—— Then, encapsulate your thoughts! See you later package
Tips: press Ctrl+H to see the inheritance tree

super -- parent class, this -- self




Here comes the difficulty
As mentioned earlier, the parameterless constructor in the subclass will execute the hidden code super(); by default;, But what happens if the parent class does not have a parameterless constructor and only has a parameterless constructor—— Burst red


So how?
Manually calling the parent class has parameters

To sum up

  • super note:

    • super calls the constructor of the parent class, which must be in the first instance of the constructor
    • super must only appear in subclass methods or constructor methods!
    • super and this cannot call constructor at the same time!
  • this note:

    • The objects represented are different
      • This: call this object itself
      • super represents the application of the parent object
    • premise
      • this: can be used without inheritance
      • super: can only be used under inheritance conditions
    • Construction method
      • this(); Construction of this class
      • super( ); Construction of parent class;

    Method override

    Look at two little chestnuts first

    • Method with static
package learn;
//Define a parent class
public class Father {

    public static void test(){
        System.out.println("B=>>");
    }

}

package learn;


//If a subclass inherits from the parent class, it inherits all the methods of the parent class
public class Son extends Father{

    public static void test(){
        System.out.println("A==>");
    }

}

package learn;

public class way {
    public static void main(String[] args) {
        Son son = new Son();

        //The subclass can point to the parent class, or the reference of the parent class points to the subclass
        Father father=new Son();
        son.test();
        father.test();
    }

}

  1. Without static, you can obviously see that there are more downward icons for the parent class and more upward icons for the child class, which is the identification of rewriting

    Tips: alt+insert can quickly generate rewrites with @ override annotation

    summary
  • Override: inheritance relationship is required. The subclass overrides the method of the parent class!
    1. The method name must be the same
    2. The parameter list must be the same
    3. Modifier: the scope can be expanded but not reduced: public > protected > Default > private
    4. Exception thrown: range, which can be narrowed but not expanded; Classnotfoundexception -- > exception (large)
  • When overridden, the methods of the child class and the parent class must be consistent; Method body is different!
  • Why to rewrite: the function of the parent class and the subclass are not necessarily required or satisfied!

polymorphic

Look at the chestnuts first

  • son inherits all the methods of the parent class
  • When subclasses are overridden, the test methods of father and son objects are overridden as subclasses
  • A parent class cannot call that is unique to a child class unless cast
package learn;
//Define a parent class
public class Father {

    public  void test(){
        System.out.println("Father");
    }

}

package learn;


//If a subclass inherits from the parent class, it inherits all the methods of the parent class
public class Son extends Father{

    @Override
    public void test() {
        System.out.println("Son");
    }

    public void eat(){
        System.out.println("Son eat");
    }
}

package learn;

public class way {
    public static void main(String[] args) {
       //The actual type of an object is determined
        //new Son();
        //new Father();

        //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class

        //The methods that Son can call are his own or inherited parent classes
        Son son = new Son();
        //Father parent class, which can point to subclasses, but cannot call methods unique to subclasses
        Father father=new Son();
        Object object=new Son();

        son.test();
        father.test();
        father.eat();//((Son) father).eat(); Force conversion


    }

}

summary
Precautions:

  1. Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
  2. Parent and child classes have associated type conversion exceptions! CLasscastException !
  3. Existence conditions: inheritance relationship, method needs to be overridden, and parent class reference points to child class object! Father f1 = new Son( );

Situations that cannot be overridden

  1. static method, which belongs to class, does not belong to instance
  2. final constant;
  3. private method;

instanceof and type conversion

instanceof

Painting inherits the trend, only the parent rotor

package learn;
//Define a parent class
public class Father {

    public  void test(){
        System.out.println("Father");
    }

}

package learn;


//If a subclass inherits from the parent class, it inherits all the methods of the parent class
public class Son extends Father{

    @Override
    public void test() {
        System.out.println("Son");
    }

    public void eat(){
        System.out.println("Son eat");
    }
}

package learn;

public class Application {
    public static void main(String[] args) {

        //Object>String
        //Object>Father>Son
        //Object>Father>Daughter

        Object object=new Son();
        System.out.println(object instanceof Son);//true
        System.out.println(object instanceof daughter);//false
        System.out.println(object instanceof Father);//true
        System.out.println(object instanceof String);//false
        System.out.println(object instanceof Object);//true
        System.out.println("==========================================");
        Father father=new Son();
        System.out.println(father instanceof Son);//true
        System.out.println(father instanceof daughter);//false
        //System.out.println(father instanceof String); The direct compilation fails because the Father class can be string, which doesn't matter
        //System.out.println(false instanceof Object); Compilation failed. Cannot convert subclass to parent
        System.out.println("==========================================");
        Son son=new Son();
        //System.out.println(son instanceof daughter); There is no relationship between the two subclasses. Compilation failed




    }

}

Type conversion

Static explanation (required)

static is loaded with the class

attribute


method


Code block

package learn;

//static
public class Application {

    //For assignment, generated simultaneously with the object
    {
        System.out.println("Anonymous code block");
    }

    //Together, only once
    static {
        System.out.println("Static code block");
    }

    public Application() {
        System.out.println("Parameterless constructor");
    }

    public static void main(String[] args) {
        Application application=new Application();
    }
}


summary

  • static code blocks, together with classes, are executed only once
  • Anonymous code blocks are executed with the created object
  • Code blocks have higher priority than constructors

Static import

abstract class


Interface

=Abstract MAx -- just write what needs to be done

package learn;

//interface definition keyword
public interface MyAction {
    //All definitions in the interface are actually Abstract public abstract s
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);

}

package learn;

public interface YourAction {
    void eat();
}

To implement multiple interfaces

package learn;

public class MyActionImpl implements MyAction,YourAction{
    @Override
    public void add(String name) {
        
    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }

    @Override
    public void eat() {

    }
}

N internal classes

Local inner class / inner class

package learn;

public class Outer {
    private int id=10;
    public void out(){
        System.out.println("This is the method of an external class");
        //Local inner class
         class Inner3{
             public void in(){
                 System.out.println("This is method 3 of the inner class");
             }
        }
    }

    //Inner class
    public class Inner1{
        public void in(){
            System.out.println("This is method 1 of the inner class");
        }
        public void getId() {
            System.out.println(id);
        }
        public void getout() {
          out();
        }

    }
}
//A Java Class can have multiple Class classes, but only one public class
//Inner class
class Inner2{
    public void in(){
        System.out.println("This is method 2 of the inner class");
    }

}


package learn;

//Static import package

public class Application {
    public static void main(String[] args) {
      Outer outer= new Outer();
      outer.out();
      Outer.Inner1 inner1=outer.new Inner1();
      inner1.getId();//Got the private property of the external class
      inner1.in();
      inner1.getout();

    }

}

Anonymous Inner Class

package learn;

//Static import package

public class Application {
    public static void main(String[] args) {
        //There is no name to initialize the class, so there is no need to save the instance to the variable~
        new Apple().eat();//Anonymous inner class, calling method directly
        new UserService() {//You can directly new an interface

            @Override
            public void add() {

            }
        };
    }

}

class Apple {
    public void eat() {
        System.out.println("1");
    }
}

interface UserService {
    void add();
}

Abnormal mechanism

Common anomalies





Catch and throw exceptions


Tips, Ctrl+alt+T, generate surrounding code blocks
Ctrl+D, directly copy the line where the current cursor is located

After catching and handling exceptions, the code can continue to run. Unlike without exception, the code terminates directly

package learn;

public class test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            System.out.println(a / b);
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Error e) {
            System.out.println("Error");
        } catch (Throwable e) {
            System.out.println("Throwable");
        } finally {
            System.out.println("finally");
        }

        try {
            new test().a();
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Error e) {
            System.out.println("Error");
        } catch (Throwable e) {
            System.out.println("Throwable");
        } finally {
            System.out.println("finally");
        }


    }


    public void a() {
        b();
    }

    public void b() {
        a();
    }
}

Take the initiative to throw

Custom exception to handle problem resolution


package learn;

//Custom exception class
public class MyException extends Exception{

    //If transfer parameter > 10
    private int detail;

    public MyException(int detail) {
        this.detail = detail;
    }

    //toString, print it out

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

package learn;

public class test {

    //There may be abnormal methods
    public static void test(int a) throws MyException {//Throw exception
        System.out.println("The parameters passed are"+a);
        if (a>10){
            throw new MyException(a);
        }
    }


    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {//Catch exception
            System.out.println("MyException=>"+e);
            e.printStackTrace();

        }
    }

}

Mind map

Topics: Java Back-end IDEA