![](/img/trans.png)
[英]Sub-class not able to access the protected method of super-class when the reference is of type super-class
[英]Can't access methods in sub class when using the super as the reference type
我有一個上課的問題
public class Foo {
public Foo() {
// Do stuff
}
public void generalMethod() {
//to general stuff
}
}
public class Bar extends Foo {
public Bar() {
//do stuff
}
public void uniqueMethod() {
//do stuff
}
}
public class Driver() {
public static void main(String[] args) {
Foo test = new Bar();
test.uniqueMethod(); //this causes an error
}
}
所以我得到一個錯誤,它說Foo的方法uniqueMethod()
是未定義的,但是當我將賦值更改為Bar test = new Bar();
問題消失了。 我不明白,因為它應該與Foo test = new Bar();
有人可以提出導致此錯誤的原因嗎?
先感謝您。
盡管該方法在運行時存在,但編譯器僅看到類型為Foo
的對象test
不具有方法uniqueMethod。 Java使用虛擬方法,其中將在runtime
確定要調用的方法。 因此,再次,編譯器看不到該特定實例的類型是Bar
。 如果確實需要調用該方法,則可以強制轉換並調用該方法:
((Bar)test).uniqueMethod();
現在,對於編譯器,您具有Bar
類型,他可以看到Bar
類型可用的所有方法。
Foo test = new Bar();
因此,我有一個Foo類型的變量。 我必須驗證對該類成員的所有后續調用都可以 -它將查找Foo
類中的所有成員,編譯器甚至不查找實例類型。
在runtime
,JVM將知道我們有一個類型為Foo
的變量,但實例類型為Bar
。 唯一的區別在於,JVM(JVM)將查找實例以對方法進行虛擬調用 。
Bar test = new Bar();
因此,我有一個Bar類型的變量。 我必須驗證對該類成員的所有后續調用都可以 -它將查找Foo
和'Bar'類中的所有成員,再次,編譯器甚至不查找實例類型。
在runtime
,JVM將知道我們有一個Bar
類型的變量和一個相同類型的實例: Foo
。 現在我們再次可以訪問Foo
和Bar
類中定義的所有成員。
使用后期綁定,您必須在超類“ Fathor”中具有相同的方法,否則將不起作用!
與我一起工作
//
public class foo {
public void print(){
System.out.println("Super,"+2);}
}
bo類擴展foo {
public void print(){
System.out.println("Sup,"+9);
}
}
測試//
公共抽象類測試{
public static void main(String[] args) {
// TODO Auto-generated method stub
foo t = new bo();
t.print();
}
} ///
輸出
一口9
發生此錯誤的原因是,編譯器不知道test
的類型是Bar
,而只知道Foo
的聲明類型。
public void test(Foo foo) {
// error! this method can accept any variable of type foo, now imagine if you passed it
// another class that extends Foo but didnt have the uniqueMethod. This just wont work
foo.uniqueMethod();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.