//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}
重写
Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
public virtual void getStuff(int id)
{
//Get stuff default location
}
}
public class test2 : test
{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}
public class A
{
public void print(int x, int y)
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public void print(float x, float y)
{
Console.WriteLine("Overload child method");
}
}
重写 (运行时多态性) : : 扩展类中具有与基类中相同名称和相同参数的函数,但具有不同的行为。
public class A
{
public virtual void print()
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public override void print()
{
Console.WriteLine("Overriding child method");
}
}
Having more than one methods/constructors with same name but different parameters is called overloading. This is a compile time event.
Class Addition
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
public static main (String[] args)
{
Addition addNum = new Addition();
System.out.println(addNum.add(1,2));
System.out.println(addNum.add(1,2,3));
}
}
营业额:
3
6
重写是一个运行时事件,这意味着根据代码在运行时更改输出。
class Car
{
public int topSpeed()
{
return 200;
}
}
class Ferrari extends Car
{
public int topSpeed()
{
return 400;
}
public static void main(String args[])
{
Car car = new Ferrari();
int num= car.topSpeed();
System.out.println("Top speed for this car is: "+num);
}
}
Notice there is a common method in both classes topSpeed().
Since we instantiated a Ferrari, we get a different result.
class Car {
public int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
variant 2 with override keyword: result is 400
class Car {
public virtual int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public override int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
关键字 虚拟的 on Car class 与 期末考试 on Java 相反,意思是 不是最终决定,如果 Car 是抽象的,可以重写或实现它
public void Wash(Truck anyTruck){
//wash the Truck
}
Wash function was only washing a Car before, but now its overloaded to wash a Truck as well.
If the provided input object is a Car, it will execute Wash(Car anyCar)
如果提供的输入对象是一个 Truck,那么它将执行
洗车(任何卡车)
让我们重写 Wash ()函数
最重要的是:
public override void Wash(Car anyCar){
//check if the car has already cleaned
if(anyCar.Clean){
//wax the car
}
else{
//wash the car
//dry the car
//wax the car
}
}