Re: [問題] 為什麼override時修飾子不能小於原來的?
※ 引述《UARTB (UART)》之銘言:
: 就是
: 為什麼要覆寫一個方法的時候
: accessibility不能小於要覆寫的原來方法呢?
: (ex: 原本是protected不能被一個private方法覆寫)
: 這樣設計有什麼優點嗎?
舉個例好了
class Base
{
public void foo()
{
System.out.println("Base");
}
}
class Derive extends Base
{
private void foo() //你的問題
{
System.out.println("Derive");
}
}
這樣一來 這裡就出問題了:
class test
{
static void bar(Base b)
{
b.foo(); //這裡
}
public static void main(String[] args)
{
foo(new Derive());
}
}
main裡傳進去的是Derive物件 照Derive說的不能讓外面呼叫
但它也"是一個"(IS-A)Base物件 照Base說的是可以讓外面呼叫的...
那所以這裡到底能不能呼叫?
為了不要發生這種負擔 (一個class並不會知道到底誰繼承他...)
於是才規定說繼承來的method其accessibility不能比原來的低
比原來的高是沒問題的:
class Base2
{
private void foo() {System.out.println("Base2");}
}
class Derive2 extends Base2
{
public void foo() {System.out.println("Derive2");}
}
class test2
{
static void basefoo(Base b)
{
b.foo(); //本來Base就是說不行 即使b其實是Derive也不行
}
static void derivefoo(Derive d)
{
d.foo(); //Derive說它行它就行 因為被蓋掉了
//這裡你也塞不進一個Base 所以沒問題
}
public static void main(String[] args)
{
basefoo(new Derive());
derivefoo(new Derive());
}
}
--
'Oh, Harry, dont't you see?' Hermione breathed. 'If she could have done
one thing to make absolutely sure that every single person in this school
will read your interview, it was banning it!'
---'Harry Potter and the order of the phoenix', P513
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.30.84
推
04/23 21:28, , 1F
04/23 21:28, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):