Notes on object-oriented programming

Notes on object-oriented programming

There are two important concepts in object-oriented

  1. Class is an abstract concept that has something in common -- such as human beings
  2. Object is a concrete concept and an instance, just like Kobe
  3. Kobe is an object, and professional basketball players are a class

There are properties and methods in a class, collectively referred to as members

Member method

  1. Member methods must be called by objects (instances)

  2. The member method wants to be an object's action, such as Kobe playing basketball

    Discuss the mechanism of parameter passing of method

    1. Parameters are divided into formal parameters and arguments
    2. The formal parameter can be regarded as a variable
    3. An argument is a concrete data
    4. A formal parameter is an interface between a method and the outside world
  3. The level of each member method is the same. Methods cannot be defined in methods

  4. Description of assignment

     1. If it is a basic data type, copy the data directly
        2. If it is a reference data type, the address in the heap will be copied directly
        3. The basic data type is independent and the reference data type is shared
    

Method recursion is very important!!! (incomplete)

There is a lot of code missing here to supplement

Comparison of method overloading and rewriting

  1. For method overloading, the method name is the same, the parameter list type is different, and others are free

  2. ***There are many requirements for rewriting * * *

    1. First, the method name must be the same, and the parameter list type must be the same
       2. The return value type is the corresponding or its subclass
       3. You cannot throw more exceptions
       4. The access modifier range cannot be reduced
       5. ***most important of all!!!!!!***
       6. Rewriting must occur in two classes that have an inheritance relationship
       7. Overloading occurs in this class
    

Variable parameter (formal parameter)

  1. That is, the number of parameters in the parameter list is uncertain
  2. Its essence is an array
  3. The argument passed in can be a * * * array***
package OverJava;

public class Unkown {
    public static void main(String[] args) {
        say(1,2,4,5,6,7,8,9);
    }
    public static void say(int... nums)
    {
        for (int i = 0; i < nums.length; i++)
        {
            System.out.println("The first"+(i+1)+"Values are"+nums[i]);
        }
    }

}

be careful

  • Variable parameters can be put together with ordinary type parameters, but variable parameter types must be at the end
  • Each method must have only one variable parameter

Scope

Variables in java are divided into global variables (attributes) and local variables

  • Local variables cannot have modifiers
  • Global variables can be modifiers
  • Local variables are in a method and can only be used by that method
  • Global variables can be called in this class or in other classes
  • Global variables have default values and local variables do not
  • Global variables die as objects are created
  • Local variables are created and die with the execution of his code block

constructor

Used to initialize instances

  1. Is a special method
  2. The method name is the same as the class name and has no return value
  3. Creating an object is an automatic call constructor

this keyword

  1. this refers to the current object

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vjYVmHmr-1636375616845)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106112346109. PNG)]

Remember that this is the current object

this() calls other constructors of this class

Package package

His essence is a folder

It is convenient to manage classes with the same name in different packages

Access modifier

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gWP4sdYL-1636375616848)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106113346244. PNG)]

For a class, it has only public and default modifiers

Again, local variables cannot have modifiers

Three characteristics of object oriented

  1. encapsulation
  2. inherit
  3. polymorphic

encapsulation

  1. Is to privatize attributes and provide public methods for protection
  2. Generally, there are getXXX(); setXXX();

inherit

  1. It is to abstract some common methods and properties in many classes and put them in a class. Then this class is called the parent class
  2. Keyword extends
  3. java only supports single inheritance
  4. The subclass inherits all the methods and properties of the parent class, but the private ones cannot be accessed directly. They can be accessed through public methods
  5. Subclasses must call the constructor of the parent class to initialize the properties and methods of the parent class
  6. Creating a subclass object is the parent class. The constructor will first call the member of the parent class to initialize the member of the subclass
  7. However, the object still has only one subclass, and only the methods and properties of the parent class are initialized in the subclass object

Look at the picture

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tJIKYORB-1636375616852)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106115246776. PNG)]

super keyword

super keyword is used to call the properties and methods of the parent class, but certain access permissions must be observed

super()

  1. Used to call the constructor of the parent class
  2. In the constructor of the subclass, there is a parameterless constructor super() by default; And on the first line

Comparison between super and this

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-3onrz02-1636375616855) (C: \ users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106120549440. PNG)]

In fact, the reason is that in the object instance, the members of the parent class and the members of the child class are independent of each other

polymorphic

What are polymorphic States

  1. The method is polymorphic
  • The rewriting and overloading issued reflect polymorphism (different objects with the same method name have different calling effects, and different parameters have different effects)

  • Polymorphism of parameters

             1. The formal parameter type is the parent type ***Argument types can be subclasses***
                2. In essence, or upward transformation
    
  1. The most important thing is the polymorphism of * * * objects***

Polymorphism of objects

  1. Objects are divided into compile type and run type

  2. Compiler type is checked by the compiler. The compiler does not check the running type

  3. Person person = new Student();//Student inherits Person
    

The compile type is Person and the run type is Student. The compiler will not check Student when checking Person

  1. In fact, upward type conversion is the automatic conversion of basic type data
  2. Downward type conversion is the casting of basic type data
Person person = new Student();//Student inherits Person
Student student = (Student) person;// Downward transformation

Talk about my understanding of parent class reference pointing to child class objects

  1. First, the compiler checks whether the properties and methods of the parent class in the code are correct when it only sees that the compiled type is the parent class
  2. That's why you can't point to methods unique to subclasses with parent class references
  3. If you want to use methods unique to subclasses, you can point to objects with subclass type references
  4. As for why I understand this (drawing on the basic data types), it may be the space opened in memory or something else is a little different
  5. Use instanceOf() to determine whether the type or its subclass is
Person person = new Student();//Student inherits Person
Student student = (Student) person;// Downward transformation
student instanceOf(Person);//true
student instanceOf(Student);//true
Object obj = new Object();
obj instanceOf(Person);//false

Talk about Object

==The difference between and equals

  1. ==Is a comparison operator and equals() is a method
  2. ==You can compare both basic data types and reference data types
  3. The basic data type depends on whether the values are equal
  4. The reference data type also depends on whether the values are equal, but the value is an address, so it depends on whether it is a common object

equals()

  1. It is a method of Object, which can only be used to judge the reference data type
  2. If it is not rewritten, it is to judge whether the addresses of the reference data types are consistent and whether they are the same object
  3. If it is rewritten, it is to judge whether the content is consistent, such as in the wrapper class and String

Here we briefly talk about hashCode, toString and finalize

  1. hashCode replaces the address of the object with a hash code value
  2. The toString method is the hexadecimal of the full class name + @ + hash value
  3. The finalize method is that when the JVM considers it a garbage object, it calls its finalize method before destroying it

Method of breakpoint debugging (incomplete)

Here later to add!!!

Class variables and class methods (static methods and static variables)

  1. Sometimes we want to share some data and methods in the same class, and class variables play a role
  2. Class variables are static and are decorated with (static)

Look at the picture

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ma4POLVr-1636375616856)(C:\Users \ story and wine \ appdata \ roaming \ typora \ typora user images \ image-20211106152449087. PNG)]

  1. About accessing class variables
  • Use class name. Class variable name
  • You can also use object name. Class variable name
  • Class variables belong to classes, so they can be accessed without objects
  1. Class variables are shared by all objects of this class, while instance variables are exclusive to each object
  2. Class variables are initialized when the class is loaded. They will be loaded when the class is loaded and die when the class dies

The idea of class method is similar to that of class variable

  • Class methods are generally used as tool classes, which can be used without creating objects
  • Such as Math.sqrt();

Comparison of class methods and member methods

  1. Class methods and ordinary methods are loaded with the loading of classes, and the structure information is stored in the method area
  2. Class method cannot have this and super
  3. Class methods can only access static methods and static variables
  4. Member methods can access both static and non static methods
  5. They all have to comply with access rights

Explain the main() method

  1. public static void main(String[] args){}
    
  2. The main() method is called by the JVM. The JVM must not be together with the main() class file you wrote, so use public

  3. The jvm calls without creating objects, so it is static

  4. Void calls the main() method and does not expect a return value, so it is void

  5. String [] is a string array that holds Java commands and parameters passed to the running class

Some notes

  1. The main method can directly call the static methods and static variables of this class, but cannot use member methods and member variables
  2. To use the member methods and member variables of this class, you must create an object

Code block

  1. The modifier of a code block can only have static
  2. The code in the code block can be any code
  3. The code block is a supplement to the constructor and can be used for initialization
  4. For example, many of the same statements in each constructor can be extracted into the initialization block to improve code reusability
  5. The data called by the code block takes precedence over the constructor
  6. The static code block is executed only when the class is loaded and only once. If it is a normal code block, it is called every time the object is created
  7. Here is a description of when the class is loaded (very important!!!)
    • Create object instance
    • The parent class of the object instance that uses the child class will also be loaded
    • When using static members of a class
  8. Ordinary code blocks are implicitly called when creating instances
  9. If only static members are used in a normal code block, the normal code block does not execute

The call order in a class when creating an object

  1. Static code blocks and static attribute initialization have the same priority. They exist at the same time and are initialized in their order
  2. The priority of common code blocks and attribute initialization is the same. If they exist at the same time, they will be initialized in their order
  3. Finally, the construction method

Let's look at the internal structure in the constructor (an understanding)

class A
{
    public A()
    {
        //Execution requirements are hidden here
        //(1) super();
        //(2) Call normal code block
        //Then execute the content in the constructor
    }
}

Call order in inheritance relationship

  1. Initialization of static code blocks and static variables of the parent class
  2. Static code block and static variable initialization of subclasses
  3. Normal code block and member variable initialization of the parent class
  4. Constructor of parent class
  5. Initialization of ordinary code blocks and ordinary member variables of subclasses
  6. Constructor of subclass

Expansion - singleton mode (incomplete)

final keyword

Final means final in Chinese

  1. final can modify class attribute method local variables
  2. It's like only final (my current understanding may not be comprehensive)
  3. A class decorated with final cannot inherit
  4. final modified methods cannot be overridden
  5. Variables decorated with final cannot be changed

abstract class

Some factors may make the method uncertain

  1. This requires an abstract method
  2. Classes containing abstract methods must be abstract methods
  3. The keyword is abstract
  4. Abstract method has no method body
public abstract void say();  // {} having curly braces means having a method body
  1. Abstract classes cannot be instantiated (besides, instantiation has no meaning, and the methods in them are empty)

  2. Abstract classes can have no abstract methods, but * * * with abstract methods, they must be abstract classes***

  3. Abstract method is essentially a class. It can have non abstract method constructors (I don't quite understand) static properties

  4. If a class inherits an abstract class, it must override all the abstract methods in it

  5. Abstract methods cannot be modified by private final static (because it violates rewriting)

Here is a best practice for abstract classes (to be added!!!)

Interface

An interface is the encapsulation of some unimplemented methods. When a class is to be used, it is rewritten according to the specific logic

Basic grammar

interface S
{
    //attribute
    //Abstract method (can be modified without abstract)
}
class A implements S
{
    //Own members
    //The method of S interface must be implemented
}

Interfaces are abstract classes. Before jdk7, methods in interfaces could not have method bodies

After jdk8, there can be static methods and default methods. In other words, there can be specific methods implemented in the interface

The interface can regulate some standards (now I'm Xiaobai and don't quite understand the magic of the interface)

be careful

  1. Interfaces cannot be instantiated (because interfaces are more abstract classes)
  2. The methods in the interface are all public, which can not be modified by abstract
  3. A common class implementation interface must implement all abstract methods
  4. Abstract classes can implement interfaces without implementing methods of interfaces
  5. A class can have multiple interfaces
  6. The attribute of an interface can only be final and public static final
  7. Interfaces cannot inherit from other classes, but they can inherit from other interfaces
  8. Interface modifiers can only be public and default

Difference between interface and inheritance

Here is a brief explanation

Inheritance satisfies is xxx

The interface satisfies like xxx

I'm also a little white. I don't have any code accumulation and don't understand it very well

  1. For the interface, it is more flexible and can be better standardized and extended
  2. Inheritance mainly solves the reusability and maintainability of code

Interface polymorphism (to be supplemented)

Briefly, the reference of an interface can point to the class that implements the interface

You can think of it this way. An interface is just a class more abstract than an abstract class (I don't know how to understand it in essence)

Therefore, you can use the reference of the interface to point to the object of the class that implements the interface

This is a simple explanation first, which will be supplemented later

Inner class

Class, the inner class of the constructor code block of the five member attribute (field) method

Internal classes are divided into

  1. Local inner class
  2. Anonymous inner class (very important!!!)
  3. Member inner class
  4. Static inner class

To sum up, it seems that only methods cannot be nested

Local inner class

The local inner class is in a local location of the external class, such as in a method, and has a class name

  1. Local internal classes can access all properties of external classes, including private ones (in fact, it is well understood that the essence of local internal classes is that external classes can access private members in the current class)
  2. The access modifier cannot be added, but the final keyword can be added (the local internal class is equivalent to a local variable)
  3. His scope is only in the method or code block that defines him
  4. Local internal class access external class members (direct access)
  5. The external class accesses the local internal class (accessed by creating an object, but * * * still has to be within its scope * * *)
  6. Other external classes cannot access local internal classes
  7. If the external class and the local internal class have the same name, follow the proximity principle. If you want to access the members of the external class, use (external class name. this. Member)

The code is missing here

Anonymous inner class (very important!!!)

  1. Nature is still a class
  2. Inner class
  3. Or an object
  4. This class has no name
//Basic grammar
//new class and interface name (parameter list)
          {Class body}; // No fewer semicolons

Other considerations are the same as local inner classes

Code demonstration

package OverJava;

public class UnName {
    public static void main(String[] args) {
        //Demonstrates three anonymous inner classes
        //abstract class
        Animal dog = new Animal(){
            public void move()
            {
                System.out.println("The dog is moving");
            }

            public void eat()
            {
                System.out.println("The dog is eating bones");
            }

            public  void sleep()
            {
                System.out.println("The dog is sleeping");
            }
        };
        dog.eat();
        dog.move();
        dog.sleep();
        System.out.println("Class of dog object"+dog.getClass());

        //General class

        Father father = new Father("jack",39){

        };
        System.out.println(father.info());
        System.out.println("father Class of object"+father.getClass());

        //Interface

        Usb meizuUsb = new Usb(){
            @Override
            public void workStart() {
                System.out.println("Meizu mobile phone interface starts working");
            }

            @Override
            public void workEnd() {
                System.out.println("Meizu mobile phone interface stops working");
            }
        };
        meizuUsb.workStart();
        meizuUsb.workEnd();
        System.out.println("meizuUsb Class of object"+meizuUsb.getClass());
    }
}

//This is an abstract class

abstract class Animal
{
    public abstract void move();
    public abstract void eat();
    public  abstract void sleep();
}

//This is a common class

class Father
{
    private String name;
    private int age;

    //constructor 
    public Father(String name, int age)
    {
        setName(name);
        steAge(age);
    }


    //setter and getter

    public String getName()
    {
        return name;
    }

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

    public int getAge()
    {
        return age;
    }

    public void steAge(int age)
    {
        if (age <= 0)
        {
            System.out.println("Your age is illogical(Has been assigned to the default value)");
            this.age = -1;

        }
        this.age = age;
    }

    public String info()
    {
        return getName() + "Hello,"+getAge()+"This is your age";
    }
}

//This is an interface

interface Usb
{
    void workStart();
    void workEnd();
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-bhLLupkr-1636375616859)(C:\Users \ story and wine \ appdata \ roaming \ typora \ typora user images \ image-20211107142735123. PNG)]

Anonymous inner classes are used to simplify development (pay attention to code accumulation)

Best practices for anonymous inner classes

Passing directly as an argument is concise and efficient (it may not feel good for me now)

Code example

package OverJava;

public class UnNameGood {
    public static void main(String[] args) {
        Master master = new Master();
        master.feed(
                new Animal_("min-hashing "){
                    @Override
                    String eat() {
                        return this.name +"Eat bones";
                    }
                }
        );
    }
}

//Define a class

class Master
{
    public void feed(Animal_ animal)//There are no parameters here
    {
        System.out.println("The master is feeding"+animal.eat());
    }

}

//Define an abstract class (animal)
abstract class Animal_
{
    String name;

    public Animal_(String name) {
        this.name = name;
    }

    abstract String eat();
}

package OverJava;

public class BestUnName {
    public static void main(String[] args) {
        Phone pandaer = new Phone("PANDAER", "17 Gray degree");
        pandaer.alarmclock(
                new Bell(){
                    @Override
                    public String ring() {
                        return "The little lazy man got up";
                    }
                }
        );
    }
}

//Analog alarm

//Define an interface
interface Bell{
    String ring();
}

//Define a mobile phone class
class Phone
{
    String name;
    String color;
    String masterName = "Story and wine";

    //constructor 
    public Phone(String name, String color)
    {
        this.color = color;
        this.name = name;
    }

    //Alarm clock method
    public void alarmclock(Bell bell)
    {
        System.out.println(color+"of"+name+"The alarm clock of the mobile phone makes a sound:"+bell.ring()+",Wake up"+masterName);
    }

}

Member inner class

The internal class of a member is defined at the position of the external class member, and cannot be decorated with static

  1. You can directly access all members of an external class, including private
  2. Any access modifier can be added because its status is a member (which can be regarded as a member variable and a collection of member variables)
  3. Since it is a member, its scope is in the whole external class;

External class ----------- internal class: the object to create the internal class is accessed again

Internal class ------------ external class: direct access, simple

Other external classes can also access member internal classes:

  1. You can write a method in an external class to return an instance (object) of an internal class
  2. You can also create objects directly
Outer.InerClass iner1 = new Outer().new InerClass();

Code demonstration

package OverJava;

public class InerClass {
    public static void main(String[] args) {
        Mater1 mater1 = new Mater1();
        mater1.say();
        mater1.say2();
    }
}

//This is an external class
class Mater1
{
    //The first way
    Outer outer = new Outer();
    Outer.InerClass iner = outer.getInerClass();

    //(the second way)
    Outer.InerClass iner1 = new Outer().new InerClass();
    public  void say2()
        {
            System.out.println("say2 Yes");
            iner1.say();
        }

    public void say()
    {
        iner.say();
    }
}

//This is a class with member inner classes
class Outer
{
    String name;
    int age;

    class InerClass
    {
        public void say()
        {
            System.out.println("I said EDG fucking great!!!");
        }

    }

    //Return an inert object in an external class (a way)
    public InerClass getInerClass()
    {
        return new InerClass();
    }

}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-rfzc633h8-1636375616861) (C: \ users \ story and wine \ appdata \ roaming \ typora user images \ image-20211107152939927. PNG)]

(the picture above is not particularly accurate. I'm Xiaobai, too)

Static inner class

  1. The static inner class has a static modifier on the member position of the outer class
  2. He can still add access modifiers. After all, his status is a member
  3. Since it is a member, of course, its scope is all of the external classes
  4. Static internal classes can directly access static variables and methods of external classes, but cannot directly access member methods and variables of external classes (through new objects)

External class ----------- static internal class: to create an object and then access it

Other external classes - static internal classes: there are also two methods

  1. The first is to create a method in the external class to return an object of a static internal class
  2. Second
Outer.iner iner1 = new Outer.iner();

My understanding: the constructor of a static internal class is equivalent to a static method, which can be called directly through the class name and method name, so external object instances cannot be created (the understanding is not necessarily accurate)

Code example

package OverJava;



public class StaticInerClass {
    public static void main(String[] args) {
        OuterOther outerOther = new OuterOther();
        outerOther.iner2.say();

        System.out.println("=========");

        outerOther.iner3.say();
    }
}

//This is an external class
class OuterOther
{
    //The first way to call a static inner class
    Outer2.Iner2 iner2 = Outer2.getIner2();

    //The second way
    Outer2.Iner2 iner3 = new Outer2.Iner2();
}

//Define a class with a static inner class
class Outer2
{
    String name;
    static class Iner2
    {
        static String name = "min-hashing ";
        public static void say()
        {
            System.out.println(name + "How do you do" );
        }
    }
    public static Iner2 getIner2()
    {
        return new Iner2();
    }
}

Conclusion

The ability of code always fails

With a strong theory, we should also have enough practice

When you write code, you should concentrate on it

I don't have him, only my hand is familiar!!!
Understanding (not necessarily accurate)

Code example

package OverJava;



public class StaticInerClass {
    public static void main(String[] args) {
        OuterOther outerOther = new OuterOther();
        outerOther.iner2.say();

        System.out.println("=========");

        outerOther.iner3.say();
    }
}

//This is an external class
class OuterOther
{
    //The first way to call a static inner class
    Outer2.Iner2 iner2 = Outer2.getIner2();

    //The second way
    Outer2.Iner2 iner3 = new Outer2.Iner2();
}

//Define a class with a static inner class
class Outer2
{
    String name;
    static class Iner2
    {
        static String name = "min-hashing ";
        public static void say()
        {
            System.out.println(name + "How do you do" );
        }
    }
    public static Iner2 getIner2()
    {
        return new Iner2();
    }
}

Conclusion

The ability of code always fails

With a strong theory, we should also have enough practice

When you write code, you should concentrate on it

I don't have him, only my hand is familiar!!!

Tags: Java

Posted on Mon, 08 Nov 2021 07:57:53 -0500 by pluginbaby