簡體   English   中英

為什么父類對子類對象的引用不能訪問子類變量?

[英]Why parent class ref to child class object cannot access child class variable?

家長班

 class Parent
        {
            int a = 10 ;
            int b = 20 ;
            int c = 50 ;

            public void display(){
                System.out.println("In Parent Class");
            }
        }

兒童班

    public class Child extends Parent{

        int c = 30 ;
        int d = 40 ;

        public void display(){
            System.out.println("In Child Class");
        }
        public static void main(String[] args) {

父類引用引用子類對象。

            Parent p = new Child();

調用父類變量

            System.out.println(p.c);

調用子類方法

            p.display();
        }
    }

似乎您想通過父引用訪問子字段變量c

Parent p = new Child();
System.out.println(p.c);

它會輸出提交Parent的 c ,您不能通過父引用訪問Child的 c ,因為通過pchild的實例,但是它是通過Parent引用訪問的,而Parent引用不能到達child的c

以及是否要打印Child的 c 您應該按如下所示downTypeCast:

Child child = (Child)(p);
System.out.println(child.c);

它將打印childc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM