Advanced knowledge of Java-classes

Advanced knowledge of Java classes

Inheritance of classes (extending classes)

Java class inheritance means that a class can inherit the properties and methods of another class, so that the subclass can reuse the code of the parent class. Inheritance is an important concept in object-oriented programming, which can help us avoid duplicating code and improve code reusability and maintainability.

In Java, inheritance is achieved using the keyword extends. After the subclass inherits the parent class, it can use the properties and methods in the parent class, and can also add its own properties and methods. Properties and methods in the parent class can be protected using the protected keyword, so that subclasses can access these properties and methods.

When a subclass inherits from a parent class, the subclass can override the methods of the parent class to implement its own functions. Subclasses can also use the super keyword to call the constructors and methods of the parent class.

Inheritance in Java is single inheritance, that is, a subclass can only inherit from one parent class. However, multiple inheritance can be implemented through interfaces in Java, and a class can implement multiple interfaces.

Inheritance is helpful for code reuse and extension, but you also need to pay attention to the reasonable use of inheritance. Excessive inheritance will increase the complexity and coupling of the code, and also affect the performance of the code. Therefore, when using inheritance, it needs to be designed and used reasonably according to the specific situation.

Inherit the constructor of the parent class

In Java, the subclass inherits the constructor of the parent class in the following situations:

  1. If the subclass does not define a constructor, it inherits the no-argument constructor of the parent class by default.

  2. If the subclass defines a constructor, you need to explicitly call the constructor of the parent class in the constructor, and you can use the super keyword to call the constructor of the parent class. For example:

public class Parent {
    
    
    public Parent(int x) {
    
    
        // 父类构造函数
    }
}

public class Child extends Parent {
    
    
    public Child(int x) {
    
    
        super(x); // 调用父类构造函数
        // 子类构造函数
    }
}
  1. If the parent class does not have a no-argument constructor, and the subclass does not explicitly call the parent class constructor, the compiler will report an error. At this time, you need to explicitly call a constructor of the parent class in the constructor of the subclass. For example:
public class Parent {
    
    
    public Parent(int x) {
    
    
        // 父类构造函数
    }
}

public class Child extends Parent {
    
    
    public Child() {
    
    
        super(0); // 调用父类构造函数
        // 子类构造函数
    }
}

Create an object of the subclass

To create an object of a subclass in Java, you can use the following steps:

  1. Define a subclass that inherits from the parent class.

  2. To define a constructor in a subclass, you can use the super keyword to call the constructor of the parent class.

  3. To create an object of a subclass in the main program, you can use the constructor of the subclass to create the object.

For example, here is a simple example showing how to create an object of a subclass:

class Animal {
    
    
    public void eat() {
    
    
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    
    
    public void bark() {
    
    
        System.out.println("Dog is barking");
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Dog dog = new Dog();
        dog.eat(); //调用父类的方法
        dog.bark(); //调用子类的方法
    }
}

In this example, the Animal class is the parent class and the Dog class is the child class. A bark() method is defined in the Dog class, which is a subclass-specific method. A Dog object is created in the main program, and then the method of the parent class and the method of the subclass are called.

Call the constructor of the parent class

In Java, you can use the super keyword to call the constructor of the parent class. The super keyword must be placed on the first line of the subclass constructor and can only be called once. The syntax for calling a superclass constructor is as follows:

public class SubClass extends SuperClass {
    
    
    public SubClass() {
    
    
        super(); // 调用父类无参构造函数
    }

    public SubClass(int arg) {
    
    
        super(arg); // 调用父类有参构造函数
    }
}

When using the super keyword in the subclass constructor to call the parent class constructor, you can use a no-argument constructor or a parameter constructor. If the parent class constructor is not called, the no-argument constructor of the parent class will be called by default.

Specify the constructor of the parent class

In Java, you can use the super keyword to call the constructor of the parent class. Following is the syntax for specifying a superclass constructor:

class Subclass extends Superclass {
    
    
    Subclass() {
    
    
        super(); // 调用父类的默认构造函数
    }

    Subclass(int x) {
    
    
        super(x); // 调用父类的带参构造函数
    }
}

In the constructor of the subclass, use the super keyword to call the constructor of the parent class. If the parent class has multiple constructors, you can choose which constructor to call according to your needs. It should be noted that if the constructor of the subclass does not explicitly call the constructor of the parent class, Java will call the default constructor of the parent class by default.

access inside subclass

protected or public in the parent class

The member variables and methods of the parent class can be accessed using the super keyword. For example, if the parent class has a member variable called "age" and a method called "getName", the subclass can use the following code to access them:

public class Parent {
    
    
    protected int age;
    protected String getName() {
    
    
        return "Parent";
    }
}

public class Child extends Parent {
    
    
    public void printInfo() {
    
    
        // 访问父类的成员变量
        System.out.println(super.age);
        // 调用父类的方法
        System.out.println(super.getName());
    }
}

In the subclass, super.age means to access the age member variable of the parent class, and super.getName() means to call the getName method of the parent class. Note that the protected modifier is used here to make the member variables and methods of the parent class to the subclass. It can be seen that if the protected or public modifiers are not used, subclasses will not be able to access them.

When the parent class has private variables, you need to use getter and setter methods. This is because private variables can only be accessed in this class and cannot be directly accessed by subclasses. Therefore, we need to define public getter and setter methods in the parent class so that subclasses can access the private variables of the parent class through these methods.

For example, suppose we have a parent class Person with a private variable name:

public class Person {
    
    
    private String name;

    public String getName() {
    
    
        return name;
    }

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

In the subclass Student, if we want to access the name variable of the parent class Person, we need to use the getter and setter methods of the parent class:

public class Student extends Person {
    
    
    public void printName() {
    
    
        System.out.println(getName());
    }

    public void changeName(String newName) {
    
    
        setName(newName);
    }
}

In the printName method, we use the getName method of the parent class to get the value of the name variable. In the changeName method, we use the setName method of the parent class to modify the value of the name variable. In this way, we can access the private variables of the parent class in the subclass.

overload

overloaded method

In Java, multiple methods with the same name can be defined in a class, as long as their parameter lists are different, this is method overloading.

Rules for method overloading:

  1. method names must be the same

  2. The parameter lists must be different (different number or type, different order also counts)

  3. The return types of the methods can be the same or different

  4. Merely having a different return type is not enough to be an overload of a method

example:

public class MyClass {
    
    
    public void print(int x) {
    
    
        System.out.println("This is an integer: " + x);
    }

    public void print(String x) {
    
    
        System.out.println("This is a string: " + x);
    }

    public void print(int x, String y) {
    
    
        System.out.println("This is an integer: " + x + " and this is a string: " + y);
    }
}

In the above example, three print methods are defined in the MyClass class. The first print method receives an integer parameter, the second print method receives a string parameter, and the third print method receives an integer parameter and a string parameter. These three methods have the same method name, but their parameter lists are different, so they constitute method overloading.

Handle objects with parameters of parent class

In Java, an object can be manipulated with parameters of the parent class. This usually involves using the concepts of inheritance and polymorphism.

First, define a method whose parameter type is the parent class in the parent class, and this method will receive an object of the parent class as a parameter. Then, override the method in the subclass and use the object of the subclass to call it.

For example, suppose there is a class Animal and a class Dog inherits from it. The Animal class has a method called makeSound() that takes an Animal object as a parameter and prints out the object's sound. In the Dog class, you can override the makeSound() method and call it with the Dog object.

Here is a sample code:

public class Animal {
    
    
    public void makeSound(Animal a) {
    
    
        System.out.println("This animal makes a sound");
    }
}

public class Dog extends Animal {
    
    
    @Override
    public void makeSound(Animal a) {
    
    
        System.out.println("This dog barks");
    }

    public static void main(String[] args) {
    
    
        Animal animal = new Animal();
        Dog dog = new Dog();
        animal.makeSound(animal); // prints "This animal makes a sound"
        dog.makeSound(dog); // prints "This dog barks"
        animal.makeSound(dog); // prints "This animal makes a sound"
    }
}

In this example, the Animal class has a makeSound() method that takes an Animal object as a parameter and prints out the object's sound. The Dog class inherits from the Animal class and rewrites the makeSound() method to use the Dog object to print out the dog's sound.

In the main() method, an Animal object and a Dog object are created. Then, use these objects to call the makeSound() method to demonstrate the concept of manipulating objects with parameters from the parent class.

The Importance of Method Overloading

The importance of Java method overloading is that it can improve the readability and maintainability of the code. Through method overloading, the same method name can be used to achieve different functions, making the code more concise and easy to understand. At the same time, method overloading can also avoid using too many method names, reduce code redundancy and duplication, and improve code reusability. In addition, method overloading can also make the code more flexible, able to adapt to different needs and situations, and improve the adaptability and scalability of the code. In short, Java method overloading is a very important part of Java programming, which can improve code quality and development efficiency.

Use a member with the same name as the parent class

In Java, if a subclass wants to use a member variable or method with the same name as the parent class, it can use the super keyword to refer to the member of the parent class.

For member variables, you can use the super keyword to access member variables of the parent class. For example:

public class Parent {
    
    
    public int x = 10;
}

public class Child extends Parent {
    
    
    public int x = 20;

    public void printX() {
    
    
        System.out.println("Child x: " + x); // 输出20
        System.out.println("Parent x: " + super.x); // 输出10
    }
}

For member methods, you can use the super keyword to call the method of the parent class. For example:

public class Parent {
    
    
    public void print() {
    
    
        System.out.println("Parent");
    }
}

public class Child extends Parent {
    
    
    public void print() {
    
    
        System.out.println("Child");
        super.print(); // 调用父类的print方法
    }
}

Using the super keyword is a convenient way to use members with the same name as the parent class in the subclass.

add final

In Java, you can use the keyword final to modify a class, indicating that the class cannot be inherited. Just add the keyword final before the class definition.

For example:

final public class MyClass {
    
    
    // 类的成员变量和方法
}

The class MyClass defined in this way is a final class and cannot be inherited by other classes.

It should be noted that if a class is declared final, then all its methods are final methods by default, that is, they cannot be overridden by subclasses. If you need to allow subclasses to override a method, you can add the keyword override before the method.

Inheritance of the Object class

Create a hierarchy of classes

  1. Define class name and access modifiers
  2. Define the properties of the class, including variables and constants
  3. Define the constructor method of the class, which is used to initialize the object
  4. Define the methods of the class, including ordinary methods, static methods and abstract methods
  5. Defines an inner class or enumeration type of a class
  6. Override the methods of the Object class, such as equals, hashCode and toString methods
  7. Implement interfaces, including single interfaces and multiple interfaces
  8. Static code block or instance code block that defines a class
  9. Defines the constructors, methods, and properties of an inner class or enumeration type of a class
  10. A static code block or an instance code block of an inner class or enumeration type that defines a class

Understand the Object class

The Java Object class is the superclass of all Java classes, which defines the default behavior that all Java classes have. The Object class has the following important methods:

  1. equals(): Compares whether two objects are equal. The default implementation is to compare the memory addresses of two objects, which can be overridden by subclasses to define their own equality logic.

  2. hashCode(): Returns the hash code of the object. The default implementation is to return the hash code of the memory address of the object, which can be overridden by subclasses to define their own hash code calculation logic.

  3. toString(): Returns the string representation of the object. The default implementation is to return a string representation of the class name and the memory address of the object, which can be overridden by subclasses to define their own string representation logic.

  4. getClass(): Returns the class object of the object.

  5. notify() and notifyAll(): Used for multi-thread synchronization to wake up threads waiting on the object.

  6. wait(): Used for multi-thread synchronization, making the current thread wait until other threads call the notify() or notifyAll() method to wake it up.

The Object class is the most basic class in the Java language, and all Java objects inherit directly or indirectly from the Object class. Therefore, the methods of the Object class are of great significance to the writing and debugging of Java programs.

Define the toString() method

In Java, the toString() method is a method in the Object class, which is used to return the string representation of the object. If this method is not overridden, the default implementation returns a string containing the object's class name and hash code.

In practical applications, programmers usually rewrite the toString() method according to their own needs, so as to better describe the state and properties of the object. For example, you can use this method to concatenate the properties of an object in string form for easy output and debugging.

The following is a sample code showing how to override the toString() method:

public class Person {
    
    
    private String name;
    private int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

In the above example, we override the toString() method to output the name and age properties of the Person object as strings. When we call this method in the program, we will get a string containing this information.

For example, the following code snippet will create a Person object and output its string representation:

Person p = new Person("Alice", 25);
System.out.println(p.toString());

The output is as follows:

Person [name=Alice, age=25]

Use the equals() method

The equals() method in Java is a method used to compare whether two objects are equal. In Java, all classes inherit the Object class. There is an equals() method in the Object class, but its default implementation is to compare whether the reference addresses of two objects are equal, that is, whether they are the same object. Therefore, if we want to compare whether the contents of two objects are equal, we need to override the equals() method.

The steps to override the equals() method are as follows:

  1. Check whether the incoming object is null, if it is null, return false directly.

  2. Check whether the incoming object is an instance of the current object, if yes, return true directly.

  3. Checks whether the incoming object belongs to the same class, if not, returns false directly.

  4. Converts the passed in object to an instance of the current class.

  5. Compare whether each attribute of the current object is equal to the attribute of the incoming object, and return false directly if any attribute is not equal.

  6. Returns true if all attributes are equal.

Here is a sample code that demonstrates how to override the equals() method:

public class Person {
    
    
    private String name;
    private int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
    
    
        if (obj == null) {
    
    
            return false;
        }
        if (this == obj) {
    
    
            return true;
        }
        if (getClass() != obj.getClass()) {
    
    
            return false;
        }
        Person other = (Person) obj;
        if (name == null) {
    
    
            if (other.name != null) {
    
    
                return false;
            }
        } else if (!name.equals(other.name)) {
    
    
            return false;
        }
        if (age != other.age) {
    
    
            return false;
        }
        return true;
    }
}

In this example, we override the equals() method of the Person class to compare the name and age properties of two Person objects for equality. The equals() method returns true if the name and age properties of the two Person objects are equal, otherwise it returns false.

Use the getClass() method

In Java, the getClass() method is a method in the Object class that can be used to obtain the runtime class of an object. Its syntax is as follows:

public final Class<?> getClass()

This method returns a Class object, which represents the class to which the current object belongs. For example:

public class MyClass {
    
    
    public static void main(String[] args) {
    
    
        MyClass obj = new MyClass();
        Class<?> c = obj.getClass();
        System.out.println(c.getName());
    }
}

In the above code, we created a MyClass object and called its getClass() method to get its runtime class. Then we use the getName() method of the Class object to get the name of the class and print it to the console. The result of the operation is:

MyClass

This shows that the getClass() method does return the MyClass class to which the current object belongs.

Guess you like

Origin blog.csdn.net/qq_36213352/article/details/130089340