Overriding member variables in Java ( Variable Hiding)

前端 未结 12 1116
小蘑菇
小蘑菇 2020-11-22 03:07

I am studying overriding member functions in JAVA and thought about experimenting with overriding member variables.

So, I defined classes

public clas         


        
12条回答
  •  时光取名叫无心
    2020-11-22 04:00

    OverRiding Concept in Java Functions will override depends on object type and variables will accessed on reference type.

    1. Override Function: In this case suppose a parent and child class both have same name of function with own definition. But which function will execute it depends on object type not on reference type on run time.

    For e.g.:

    Parent parent=new Child();
    parent.behaviour();
    

    Here parent is a reference of Parent class but holds an object of Child Class so that's why Child class function will be called in that case.

    Child child=new Child();
    child.behaviour();
    

    Here child holds an object of Child Class, so the Child class function will be called.

    Parent parent=new Parent();
    parent.behaviour();
    

    Here parent holds the object of Parent Class, so the Parent class function will be called.

    1. Override Variable: Java supports overloaded variables. But actually these are two different variables with same name, one in the parent class and one in the child class. And both variables can be either of the same datatype or different.

    When you trying to access the variable, it depends on the reference type object, not the object type.

    For e.g.:

    Parent parent=new Child();
    System.out.println(parent.state);
    

    The reference type is Parent so the Parent class variable is accessed, not the Child class variable.

    Child child=new Child();
    System.out.println(child.state);
    

    Here the reference type is Child, so the Child class variable is accessed not the Parent class variable.

    Parent parent=new Parent();
    System.out.println(parent.state);
    

    Here the reference type is Parent, so Parent class variable is accessed.

提交回复
热议问题