Home  >  Article  >  Java  >  Java Example - Method Overriding

Java Example - Method Overriding

黄舟
黄舟Original
2017-02-16 10:17:111340browse

In the previous chapter, we have learned about the rewriting of Java methods. In this article, we will look at the implementation of Java method coverage.

The difference between method overloading and method overwriting is as follows:

  • Method overloading (Overloading): If there are two methods with the same method name but inconsistent parameters, what? You can say that a method is an overload of another method.

  • Method overriding: If a method is defined in a subclass, its name, return type and parameter signature are exactly the same as the name, return type and parameters of a method in the parent class If the signatures match, it can be said that the method of the subclass overrides the method of the parent class.

The following example demonstrates the implementation of Java method overriding (Overriding) code:

/*
 author by w3cschool.cc
 Findareas.java
 */public class Findareas{
   public static void main (String []agrs){
      Figure f= new Figure(10 , 10);
      Rectangle r= new Rectangle(9 , 5);
      Figure figref;
      figref=f;
      System.out.println("Area is :"+figref.area());
      figref=r;
      System.out.println("Area is :"+figref.area());
   }}class Figure{
   double dim1;
   double dim2;
   Figure(double a , double b) {
      dim1=a;
      dim2=b;
   }
   Double area() {
      System.out.println("Inside area for figure.");
      return(dim1*dim2);
   }}class Rectangle extends Figure {
   Rectangle(double a, double b) {
      super(a ,b);
   }
   Double area() {
      System.out.println("Inside area for rectangle.");
      return(dim1*dim2);
   }}

The output result of running the above code is:

Inside area for figure.
Area is :100.0
Inside area for rectangle.
Area is :45.0

The above is Java Example - Content covered by the method. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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
Previous article:Java Example - FactorialNext article:Java Example - Factorial