Day18 object oriented 03

Day18 object oriented 03

Object oriented method rewriting

  • The method introduce() of the parent class can no longer meet the needs of the child class. What should I do? Similarly, toString() of Object class cannot meet the requirements of Animal class and Dog class. What should I do? It can be solved by method override, or called method override
public class dog extends animal{
    private String nickname;

    public dog(){

    }

    public dog(String colour,int age,String nickname){
        super(colour,age);
        this.nickname=nickname;
    }


    public void guard(){
        System.out.println("guarding......");
    }

    @Override
    public void introduce() {
        super.introduce();
        System.out.println(nickname);
    }

    @Override
    public String toString() {
        return "dog[colour="+super.colour+"age="+super.getAge()+"]";
    }
}

-----------------------------------------
public class animal {
    protected String colour;
    private int age;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge(){
        return age;
    }

    public animal(){

    }

    public animal(String colour,int age){
        this.colour=colour;
        this.age=age;
    }


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

    public void introduce(){
        System.out.println(colour+age);
    }

    @Override
    public String toString() {
        return colour+age;
    }
}
--------------------------------------
    public class test {
    public static void main(String[] args) {
        dog d1 = new dog("blue",2,"Hook");
        d1.eat();
        d1.guard();
        d1.introduce();//The method of the parent class cannot meet the requirements of the child class and needs to be overridden
        System.out.println("======================");
        System.out.println(d1.toString());//There is no toString in dog --- > go to animal to find (no) ---- > and finally to object
        //If the parameter of println is an object, its tostring is called by default


    }
}

The difference between method rewriting and overloading

  • These two are two important concepts of object-oriented
englishDifferent locationDifferent functions
heavy loadoverloadIn the same classProvide multiple implementation methods for a behavior in a class and improve readability
rewriteoverrideBetween subclass and parentThe method of the parent class cannot meet the requirements of the child class. The child class meets the requirements through method rewriting
Modifier Return valueMethod nameparameterThrow exception
heavy loadirrelevantirrelevantidenticalDifferentirrelevant
rewriteGreater than or equal toLess than or equal toidenticalidenticalLess than or equal to

Rewrite instance: toString() equals() hashCode() of Object class can be overridden by subclasses

  1. Some methods use the final modifier and cannot be overridden, such as wait() notify() of the Object class
  2. Static methods cannot be overridden. In JAVA, if the parent class contains a static method and the subclass also contains a static method with the same return type, method name and parameter list, the subclass actually hides the method with the same name as the parent class instead of overriding it. Adding @ override annotation will report an error and can be called directly through the class name Use.

Recognize Object class

  • The Object class is the root and base class of all Java, which means that all Java objects have the properties and methods of the Object class. If the extends keyword is not used to indicate its parent class in the class declaration, the Object class is inherited by default.

Interview topic: write 6 methods of Object class

booleanequals(Object obj) indicates whether other objects are "equal" to this object
Class<?>getClass() returns the runtime class of this Object
inthashCode() returns the hash code value of the object
voidnotify() wakes up a single thread waiting on this object monitor
voidnotifyAll() wakes up all threads waiting on this object monitor
StringtoString() returns the string representation of the object
voidwait() causes the current thread to wait until another thread calls the notify() or notifyAll() methods of this object, or the specified amount of time is exceeded
voidwait(long timeout) calls the notify() or notifyAll() methods of this object in other threads, causing the current thread to wait
voidwait(long timeout,int nanos) causes the current thread to wait before another thread calls the notify() or notifyAll() method of this object, or another thread interrupts the current thread, or the actual amount of time has exceeded
  • The above is the public method of the Object class

Extension: native keyword

  • A native method is an interface for Java to call non java code. A native method means that the implementation of the method is implemented by non java languages, such as C and C + +
  • When defining a native method, the implementation is not provided because it is implemented outside by a non Java language. The Java language itself cannot access and operate the bottom layer of the operating system, but other languages can be called through the JNI interface to access the bottom layer.
  • JNI is a Java Native Interface. It is a native programming interface. It is part of the Java Software Development Kit (SDK). JNI allows java code to use code and code libraries written in other languages. The invocation API (part of JNI) can be used to integrate Java virtual machines (JVM s) Embedded in native applications, allowing programmers to call java code from within native code
private static native void registerNatives();
static{//Static code block
    registerNatives()
}

Hiding member variables

  • If the parent class and the child class have member variables with the same name, there is no rewriting of variables and each occupies its own space. The member variables of the child class take precedence, which is called the hiding of member variables

Calling procedure (super) of construction method in case of inheritance

Execution order of construction methods under inheritance conditions

  • The first statement of the constructor defaults to super(), which means calling the constructor without parameters of the parent class
  • The first statement of the constructor can be explicitly specified as the parameterized constructor of the parent class: super(...)
  • The first statement of the constructor can be explicitly specified as the constructor this(...) of the current class

matters needing attention

  • Each class should preferably provide a parameterless constructor
  • The first statement of the construction method can be the construction method through super or this call. It must be the first statement
  • The constructor cannot be called with super and this at the same time, which does not mean that the two cannot occur at the same time

Alt + insert quick construction method, get/set method

Super can call the construction method super(colour,age);

Super can call the member variable (within the permission range) super.introduce;

Super can call the method (or super.colour of the parent class);

  • Super can be regarded as a reference to the direct parent object. Each subclass object will have a super reference to its direct parent object
public class animal {
    private String colour;
    private int age;

    public animal() {
        super();//The parameterless constructor of the parent class is called by default
        System.out.println("==============GOUZAO=========");
    }

    public animal(String colour, int age) {
        super();//The parameterless constructor of the parent class is called by default
        this.colour = colour;
        this.age = age;
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "animal{" +
                "colour='" + colour + '\'' +
                ", age=" + age +
                '}';
    }
}
---------- animal class--------------
    
    
----------dog class-------------------
public class dog extends animal{
    private String Nickname;
    private String type;

    public dog() {
        super();
        System.out.println("=============dog============");
    }

    public dog(String colour, int age, String nickname) {
        super(colour, age);
        Nickname = nickname;
    }

    public dog(String colour, int age, String nickname, String type) {
        //Case 1: super() calls the parameterless constructor of the parent class
        //Case 2: super(colour, age); call the constructor with parameters
        //super(colour, age); if this is not written, the parameterless calling method of the parent class will be called by default
        //Case 3: this(colour,age,nickname)
        super(colour, age);
        Nickname = nickname;
        this.type = type;
    }

    public String getNickname() {
        return Nickname;
    }

    public void setNickname(String nickname) {
        Nickname = nickname;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String  toString() {
        return "dog{" +super.getColour()+" "+super.getAge()+" "+
                "Nickname='" + Nickname + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
}



----------TEST class-------------------
public class TEST {
    public static void main(String[] args) {
        dog d1 = new dog();

        dog d2 = new dog("white",2,"mimi","american");
        System.out.println(d2);
    }
}

equals method

combination

  • Inheritance and composition are two ways to reuse code:

Inherit is-a Dog is-a Animal Cat is-a Animal

Combination has-a computer has-a CPU memory mainboard

Composition is to take a class as a member variable of a class

Extension: one of the object-oriented design principles: the principle of composition, aggregation and reuse (composition is preferred rather than inheritance)

  • Unless the two classes are in the relationship of is-a, do not use inheritance easily. Do not use inheritance simply to realize code reuse, because excessive use of inheritance will destroy the maintainability of the code. When the parent class is modified, it will affect all the subclasses inherited from it, thus increasing the maintenance difficulty and cost of the program
  • Don't use inheritance just to achieve polymorphism. If there is no is-a relationship between classes, you can achieve the same purpose by implementing interface and combination. The policy pattern in design pattern can well illustrate this. Using interface and combination has better scalability than inheritance
public class cpu {
    public void calc(){
        System.out.println("cpu.calc");
    }

    public void ctrl(){
        System.out.println("cpu control");
    }
}

public class memory {
    public void store(){
        System.out.println("memory cunchu");
    }
}

public class mainboard {
    public void connect(){
        System.out.println("mainboard connect");
    }
}

public class computer {
    private cpu cpu1 = new cpu();
    private memory memory1 = new memory();
    private mainboard mainboard1 = new mainboard();


    public void work(){
        cpu1.calc();
        cpu1.ctrl();
        memory1.store();
        mainboard1.connect();
    }

    public static void main(String[] args) {
        computer c1 = new computer();
        c1.work();
    }
}

Object oriented design principles

  • Single responsibility principle
  • Opening and closing principle
  • Richter substitution principle
  • Dependency injection principle
  • Interface separation principle
  • Dimitri principle
  • Combination / aggregation Reuse Principle OK

Create mode 5 + 1

  • Simple factory mode
  • Factory method model
  • Abstract factory pattern
  • Creator mode
  • Prototype mode
  • Singleton mode

Structural model

  • Appearance mode
  • Adapter mode
  • proxy pattern
  • Decoration mode
  • Bridging mode
  • Combination mode
  • Sharing element mode

Behavioral model

  • Template method pattern
  • Observer mode
  • State mode
  • Strategy mode
  • Responsibility chain model
  • Command mode
  • Visitor mode
  • Mediator mode
  • Memo mode
  • Iterator mode
  • Interpreter mode

Introduce polymorphism

  • Polymorphism is one of the three characteristics of object-oriented. The same behavior can reflect different forms through different subclasses.

Polymorphism refers to the same method call, which may have different behavior due to different objects. In real life, the specific implementation of the same method will be completely different.

Example: it is also the method of calling people's "rest". Zhang San is sleeping and Li Si is traveling....

Compiler type refers to the type on the left and runtime type refers to the type on the right. When there is an inheritance relationship, the compiler type and run-time type may be different, that is, the compiler type is the parent type and the run-time type is the subclass type. That is, the parent class reference points to the child class object

Key points of polymorphism:

  1. Polymorphism is the polymorphism of methods, not attributes (polymorphism has nothing to do with attributes)
  2. There are three necessary conditions for polymorphism: inheritance, method rewriting, and parent class reference pointing to child class objects
  3. After the parent class reference points to the child class object, the method overridden by the child class is called with the parent class reference, and polymorphism occurs
public class Programmer {
    private String name = "proName";//Polymorphism has nothing to do with member variables and is related to overridden methods

    //Methods inherited by subclasses
    public void writecode(){
        System.out.println("writecode");
    }
    //Subclass override method
    public void eat(){
        System.out.println("eat");
    }
}

public class cnpro extends Programmer{

    //Inherited method writecode()


    //Overridden method (eat)


    @Override
    public void eat() {
        System.out.println("Eat with chopsticks");
    }

    //Subclass specific approach
    public void liantaiji(){
        System.out.println("cn play taiji");
    }
}

public class english extends Programmer{
    @Override
    public void eat() {
        System.out.println("Eat with a knife and fork");
    }

    public void racehouse(){
        System.out.println("English Horse Racing");
    }
}

public class ita extends Programmer{
    @Override
    public void eat() {
        System.out.println("Indians eat with their hands");
    }

    public void football(){
        System.out.println("Indians like playing football");
    }
}

public class cartoon  {
    public static void showeat(Programmer pro){
        pro.eat();
    }
/*
    public static void showeat(english pro){
        pro.eat();
    }

    public static void showeat(cnpro pro){
        pro.eat();
    }

    public static void showeat(ita pro){
        pro.eat();
    }*/

    public static void main(String[] args) {
        //Programmers eat
        Programmer pro = new Programmer();
        showeat(pro);

        //Chinese programmers eat
        cnpro cn = new cnpro();
        //An argument can be a reference to any subclass object
        showeat(cn);
        //British programmers eat
        ita it = new ita();
        showeat(it);//Programmer pro = it
    }

}

Tags: Java Interview

Posted on Tue, 12 Oct 2021 13:34:49 -0400 by john_bboy7