Overloading and rewriting in Java

The difference between overloading and rewriting

Overloading occurs in the same class, the same method, with different parameter lists and different return value types; You can have different access rights

Rewriting occurs on a subclass and is also for the same method, except that the parameter list and order must be completely consistent with the parent class, the return value type must be less than or equal to the parent class, the thrown exception must be less than the parent class, and the access modifier must be greater than or equal to the parent class

The rewriting of methods should follow the principle of two identical, two small and one large. Please explain

Overloaded example

Create a father class and sell melons

public class Father {
    /**
     * 卖瓜的人是谁
     */
    private String name;
    /**
     * 状态
     */
    private Integer status;
    /**
     * 成本
     */
    private Double cost;


    public Father() {
    }

    public Father(Integer status,Double cost) {
        this.status = status;
        this.cost = cost;
    }
}

The following are the overloaded methods in the father class. To sum up, all conditions must be met

public void doSomething() {
        System.out.println("大家好,我是卖瓜的");
    }

public void doSomething(String name) {
    System.out.println("大家好,我是卖瓜的,我的名字叫:" + name);
}

public double doSomething(double money) {
    System.out.println("卖瓜营业额:" + money);
    final double profit = money - this.cost;
    System.out.println("除去成本,还剩:" + money);
    return profit;
}

⚠️ The following are examples of errors

Rewrite example

Let's now add the previous method to the father class

 /**
 * 来自父亲的感慨
 * @return
 * @throws Exception
 */
protected Father selfEvaluation() throws Exception {
    System.out.println("父亲正在感慨中....");
    throw new Exception("在感慨的时间里,被偷了两个瓜");
}

New is a son class that inherits from father. Son doesn't want to sell melons and wants to do something by himself

public class Son extends Father {

    @Override
    public void doSomething() {
        System.out.println("我父亲是卖瓜的,但我不想卖瓜,我想干点其他的");
    }


    @Override
    public Son selfEvaluation() throws illegalaccessexception {
        System.out.println("儿子正在感慨中....");
        throw new illegalaccessexception("在感概的时间里,被老板抓住了,扣了20块钱工资");
    }
}

We notice that son overrides the parent class

So, smart you, did you find anything? (principle of Rewriting: two are the same, two are small and one is large)

result

Father father = new Father(1,10D);
father.doSomething();
father.doSomething("码农Amg");
father.doSomething(30D);
father.selfEvaluation();

System.out.println("----------------------------------");

Father son = new Son();
son.doSomething();
son.selfEvaluation();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>