Access variable using parent reference type in java

I created 2 classes - Parentand Child, and so:

Parent.java

public class Parent {
    String name = "Parent";
}

Child.java

public class Child extends Parent {
    String name = "Child";
}

The Child class obscures the instance variable of the parent class name.

I created the main program as follows:

Test.java

public class Test {

    public static void main(String[] args) {
        Parent p = new Parent();
        Child c = new Child();

        System.out.println(p.name);
        System.out.println(c.name);

        Parent pc = new Child();
        System.out.println(pc.name);
    }

}

The output of the program is as follows:

Parent
Child
Parent

Now I do not understand when I try to access pc.name, then I get the output as Parentin accordance with the above output instead Child.

, pc Parent, Child . java , name, pc.name Child. , , .

, ?

+4
4

( : ). , (a.k.a "", "" ) .

: , , . pc.name. pc, , Parent , , , .name Parent.

+5

.

Child name. Child Parent (BTW, ).

name Parent, name Parent. name Child, name Child.

+7

:

  • , , .
  • Shadowing , , , .

:

public class Parent {
    String name = "Parent";
    public void printName(){
    System.out.println("Parent Method");
  }
}

public class Child extends Parent {
  String name = "Child";
  public void printName(){
    System.out.println("Child Method");
   }
}

main() Test Class: -

public class Test {

public static void main(String[] args) {
    Parent p = new Parent();
    Child c = new Child();

    System.out.println(p.name); // will print Parent name
    System.out.println(p.printName());// will call Parent
    System.out.println(c.name); // will print Child name
    System.out.println(c.printName());// will call Child

    Parent pc = new Child();
    System.out.println(pc.name);// will print Parent name
    System.out.println(pc.printName());// will call Child
   }
}

, : -

Parent 
Parent Method
Child
Child Method
Parent
Child Method
+1

u Child java, , super. , "", ""? . , Child.   , . , , / - -, , ?

Access to variables is always allowed, as a static type is allowed (i.e.: variable type) at compile time. However, methods that are determined by the runtime type of the actual object. In this program, s.name will be resolved on COMPILE-TIME itself. That is, s.name will be allowed for Shape.name Obviously, now the result should be Shape.

0
source

All Articles