How to override method in java?
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)].
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.
The output is:
#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.
At this time, the system outputs the Polygon class name and its attributes in string form.
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:
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
