个性化阅读
专注于IT技术分析

Java方法重写

点击下载

本文概述

如果子类(子类)有相同的父类中声明的方法,它被称为方法覆盖在Java中。

换句话说,如果一个子类提供了该方法的具体实现,宣布了它的一个父类,它被称为方法覆盖。

使用Java方法覆盖

  • 方法重写是用来提供的具体实现方法已由其超类。
  • 方法覆盖用于运行时多态

Java方法重写规则

  1. 该方法必须与父类相同的名称
  2. 的方法必须具有相同的参数作为父类。
  3. 一定有一个是一个关系(继承)。

理解问题没有办法覆盖

让我们明白我们可能面临的问题,这个项目如果我们不使用方法覆盖。

//Java Program to demonstrate why we need method overriding
//Here,we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
  void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
  public static void main(String args[]){
  //creating an instance of child class
  Bike obj = new Bike();
  //calling the method with child class instance
  obj.run();
  }
}

输出:

Vehicle is running

问题是我需要提供的具体实现()方法运行子类重写这就是为什么我们使用方法。


方法覆盖的例子

在这个例子中,我们定义了运行方法在子类中定义父类,但有一些特定的实现。方法的名称和参数都是一样的,而且是一个类之间的关系,这是最重要的方法。

//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
  //defining a method
  void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
  //defining the same method as in the parent class
  void run(){System.out.println("Bike is running safely");}

  public static void main(String args[]){
  Bike2 obj = new Bike2();//creating object
  obj.run();//calling method
  }
}

输出:

Bike is running safely

Java方法覆盖的一个真实的例子

考虑这样一个场景,银行是一个类,它提供了功能的利率。然而,根据银行利率的变化。例如,印度国家银行ICICI和AXIS银行可以提供8 07年��0和9�利率。

Java方法覆盖主要是用于运行时多态中我们将学习下一个页面。

//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

我们可以覆盖静态方法吗?

不,一个静态方法不能被覆盖。它可以证明运行时多态,所以我们将学习它。


为什么我们不可以覆盖静态方法?

因为静态方法是用类实例方法则是用一个对象。静态属于类地区,属于一个实例堆区域。


我们可以覆盖主要java方法吗?

不,因为主要是一个静态方法。


方法重载和方法重写java的区别

点击我的方法重载和重写的区别


赞(0)
未经允许不得转载:srcmini » Java方法重写

评论 抢沙发

评论前必须登录!