Re: [問題] 禁止子類別宣告與上層變數名稱相同的變數
※ 引述《PsMonkey (痞子軍團團長)》之銘言:
: ※ 引述《kenl (ken)》之銘言:
例如我有一個變數 int counter
在程式每個 class (包括inner class)中都共用
如果別人(或者將來的我)
在 inner class 中再宣告 int counter=0
這樣 complier 會完全沒有 warning
(之前在這個 inner class 中一直使用外面的 counter
現在變成 inner class裡的counter都變成0了
我想知道有沒有方法
使得將來的我在這個 inner class 中宣告 int counter時
會知道這樣會影響之前在這個inner class中使用外面counter的程式碼
)
我知道如果當初寫程式時
每次都明確寫成 this.counter 或 parent.counter
這樣的話將來在 inner class 再宣告counter時
也不會有bug,但這樣很不方便
: : 例如:
: : class A{
: : int i;
: : class B{
: : int i; // 這行的i會在class B的scope中覆蓋class A中的 i
: : }
: : }
: : 我問題是能不能在class A宣告 int i 時
: : 就限制底層不能把它覆蓋 ?
: : 我用protected好像不行...
: 覆蓋? 我實在很想說:「請定義一下『覆蓋』的意思」
: 不過,這好像有點瞎...
: 還是來寫程式吧...
: public class Test {
: int a;
: Foo foo;
: class Foo{
: int a;
: Foo(){
: this.a=100;
: }
: public String toString(){
: return ""+a;
: }
: }
: public String toString(){
: return "this.a="+a + "\n foo.a="+foo.a + "\n "+foo;
: }
: Test(){
: foo = new Foo();
: this.a=-1;
: }
: public static void main(String[] args) {
: Test a = new Test();
: System.out.println(a);
: }
: }
: 當然,如果你只是要別人不能取同樣的名字...
: ㄜ... 阿.... Orz
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.90.200
推
03/10 13:44, , 1F
03/10 13:44, 1F
推
03/10 13:45, , 2F
03/10 13:45, 2F
討論串 (同標題文章)