search
HomeJavajavaTutorialHow to override method in java?

How to override method in java?

Jun 24, 2020 pm 03:08 PM
javarewrite

Methods for method rewriting: 1. [toString()] method, returns an object in the form of a string; 2. [equals()] method, compares whether the references of two objects are equal, code It is [sq s2=new sq(5,4);println(s1.equals(s2)].

How to override method in java?

Rewritten by the method in java Method:

The rewriting of methods in Java is based on one of the three major characteristics of the Java class: inheritance. Without inheritance, we cannot talk about method rewriting. Method rewriting is an operation in which when a method of the parent class in the program cannot meet the needs of the subclass, the subclass can redefine the content and function of the method to meet the needs of the subclass. So rewriting of methods Specifically how to implement it through code, the blogger below will take you to find out.

(1) Define a polygon class

class Polygon{
//属性
private int number_side;
//构造器
public Polygon(int number_side) {
super();
this.number_side = number_side;
}
//方法
public int getNumber_side() {
return number_side;
}
public void setNumber_side(int number_side) {
this.number_side = number_side;
}
public void show(){
System.out.println("Number_side is " + this.number_side);
}
}

In this class, in addition to the get and set methods In addition, there is also a show method that can output the number of polygon sides.

(2) Define a square class inherited from the polygon class

class square extends Polygon{
//属性
private double length; 
//构造器
public square(double length, int number_side) {
super(number_side);
this.length = length;
}
//方法
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
//输出边数和边长
public void show(){
System.out.println("This is a square");
super.show();
System.out.println("Length is " + this.length);
}
}

You can see that there is still a show in the subclass square method, but the function and statement of the method are quite different from the show method in its parent class. Because, in the subclass square, the function of the show method of the subclass square must not only be able to output the number of sides, but also the length of the sides output, so the show method of the parent class cannot meet the needs of the subclass at this time. The developer should rewrite a show method to meet the needs of the subclass. This is method rewriting in java.

In the actual development process, there are many other situations where method rewriting is applied. Next, this article will list several more commonly used method rewriting.

  Under the java.lang package of java There is a class named Object. Object is a special class, which is the parent class of all classes. When we create a class, if we do not declare it to inherit from the class we created ourselves, then it will inherit from Object, only However, the extends Object keyword is omitted in java. There are two frequently used methods in the Object class: 1.toString() method; 2.equals() method. These two methods are often repeated in classes created by developers. Write.

1. toString() method

The function of toString() method is to return an object in the form of a string. For example :

Polygon p = new Polygon(3);
System.out.println(p.toString());

The toString() method called here is the toString() method in the Object class.

How to override method in java?

The output is:

How to override method in java?

#It can be seen that when the toString() method in the Object class is called, an object in the form of a string is returned. , that is, the address of the object.

In actual applications, the toString() method is usually overridden to provide a specific string output mode for the object, for example:

public class Test {
public static void main(String[] args) {
Polygon p = new Polygon(3);
System.out.println(p.toString());
}
}
class Polygon{
//属性
private int number_side;
//构造器
public Polygon(int number_side) {
super();
this.number_side = number_side;
}
//..................................此处省略其他无关的方法
@Override
public String toString() {
return "Polygon [number_side=" + number_side + "]";

In the polygon class Polygon The toString() method has been rewritten. In the main method, we create a Polygon object p and instantiate it, and call the rewritten toString() method in Polygon.

How to override method in java?

At this time, the system outputs the Polygon class name and its attributes in string form.

How to override method in java?

2. The equals() method

The specific embodiment of the equals() method in the Object class What is it like? What is its function? The old rule is to go directly to the code.

public boolean equals(Object obj) {
        return (this == obj);
    }

This is the specific implementation of the equals() method of the Object class in the source code, so we know that the function of the equals() method in Object is to compare Whether the references of two objects are equal. When we call the equals() method in the Object class:

public class Test {
public static void main(String[] args) {
square s1 = new square(5.2,4);
square s2 = new square(5.2,4);
System.out.println(s1.equals(s2));
}
}

The output of the system is:

How to override method in java?

Then we rewrite equals()method in the square class

public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
square other = (square) obj;
if (Double.doubleToLongBits(length) != Double
.doubleToLongBits(other.length))
return false;
return true;
}

When the equals()method in the square class is called again

public class Test {
public static void main(String[] args) {
square s1 = new square(5.2,4);
square s2 = new square(5.2,4);
System.out.println(s1.equals(s2));
}
}

the output of the system is:

How to override method in java?

Compared with the previous fasle, the output of true at this time is because the equals() method is rewritten, and the rewritten equals( )The method compares the actual contents of the two objects, that is, the attributes of the two objects (note: the equals() method does not compare the methods of the two objects because it is meaningless), and outputs true if they are equal.

The above is the basic knowledge about method rewriting and some common points. The blogger mentioned before in the chapter on polymorphism: method rewriting is also a manifestation of polymorphism. Now we can know that they are also toString() and equals () method, after being rewritten in a custom class, has completely different functions from the Object class. This is also a different manifestation of the same thing, which is in line with the nature of polymorphism.

Recommended tutorial: "java video tutorial"

The above is the detailed content of How to override method in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?Apr 19, 2025 pm 08:27 PM

When using MyBatis-Plus or tk.mybatis...

How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?Apr 19, 2025 pm 08:24 PM

How to query personnel data through natural language processing? In modern data processing, how to efficiently query personnel data is a common and important requirement. ...

How to parse next-auth generated JWT token in Java and get information in it?How to parse next-auth generated JWT token in Java and get information in it?Apr 19, 2025 pm 08:21 PM

In processing next-auth generated JWT...

Why can't JavaScript directly obtain hardware information on the user's computer?Why can't JavaScript directly obtain hardware information on the user's computer?Apr 19, 2025 pm 08:15 PM

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Apr 19, 2025 pm 08:12 PM

RuoYi framework circular dependency problem troubleshooting and solving the problem of circular dependency when using RuoYi framework for development, we often encounter circular dependency problems, which often leads to the program...

When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?Apr 19, 2025 pm 08:09 PM

About SpringCloudAlibaba microservices modular development using SpringCloud...

Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)