为什么我们需要将方法显式定义为虚拟,然后在C#中指定override来完成方法重写,而在Java中不使用这两个关键字的情况下实现相同的操作。它有什么用途?
答案 0 :(得分:6)
在java中,没有必要添加任何关键字来覆盖方法。但是有些规则适用:
答案 1 :(得分:3)
通过这种方式,您可以更严格地控制可覆盖的内容。它与访问权限相同 - 您是默认情况下为用户授予所有权限并删除权限,还是不提供任何权限,然后添加所需内容。
答案 2 :(得分:0)
函数重写意味着“具有相同名称且具有相同参数的不同方法”。 在这里,我附上一个关于覆盖的小代码。
这里我使用基类的“虚拟”关键字。 如果我们想调用派生类,那么我们必须使用“覆盖”关键字。
要调用基类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Function_Overriding
{
public class Program
{
public virtual void display()
{
Console.WriteLine("This is Function Overriding");
}
public virtual void rnreddy()
{
Console.WriteLine("This is Possible because of RN Reddy");
}
static void Main(string[] args)
{
Program dc = new Program();
dc.display();
dc.rnreddy();
Console.ReadLine();
}
}
}
调用派生类
class TestOverride
{
public class Employee
{
public string name;
// Basepay is defined as protected, so that it may be accessed only by this class and derrived classes.
protected decimal basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal salesbonus;
// The constructor calls the base-class version, and initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay, decimal salesbonus) : base(name, basepay)
{
this.salesbonus = salesbonus;
}
// Override the CalculatePay method to take bonus into account.
public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}
static void Main()
{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
Employee employee2 = new Employee("Bob", 1200);
Console.WriteLine("Employee4 " + employee1.name + " earned: " + employee1.CalculatePay());
Console.WriteLine("Employee4 " + employee2.name + " earned: " + employee2.CalculatePay());
}
}
/*
Output:
Employee4 Alice earned: 1500
Employee4 Bob earned: 1200
*/