Thoughts on assigning child classes to parent classes and assigning child classes

Source: Internet
Author: User

Thoughts on assigning child classes to parent classes and assigning child classes

2014-3 3

13:57:48

 1 /**  2  * @author nlee 3  * @version 1:09:38 PM Dec 3, 2014 4  */ 5 package test; 6  7 public class T extends T1 8 { 9     int b;10 11     public T(int s1)12     {13         super(s1);14         b = 111;15     }16 17     public void fun2()18     {19         System.out.println("T===fun2");20     }21 22     public static void main(String[] args)23     {24         T t = new T(5);25         t.fun1();26         t.fun2();27         System.out.println(t.b);28         System.out.println(t.a);29         T1 t1 = t;30         t1.fun1();31         t1.fun2();32         System.out.println(t1.a);33         // System.out.println(t1.b);34     }35 }36 37 class T138 {39     int a;40 41     public T1(int s)42     {43         a = s;44     }45 46     public int get()47     {48         return a;49     }50 51     public void set(int d)52     {53         a = d;54     }55 56     public void fun1()57     {58         System.out.println("T1---fun1");59     }60 61     public void fun2()62     {63         System.out.println("T1---fun2");64     }65 }

33 lines of commented code

33         // System.out.println(t1.b);

If the command is executed, an error is returned.

Because 29 lines of code

29         T1 t1 = t;

Assign the subclass object instance to the parent class object. t1 and t point to the same memory block, but t1 cannot access the subclass field. Therefore, t1 cannot access variable B.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.