zoukankan      html  css  js  c++  java
  • 对于父类的私有属性,子类是从哪里访问到的?

    其实也是牵扯到子类继承父类时,父类的private属性在子类中是什么样的问题。
    根据JAVA官方的定义:
    A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
    A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

    子类是无法继承父类的private成员的,但是在子类对象的内存里有没有父类的private成员呢?来看以下的代码:

    package cn.haiyisoft3;
    
    public class ExtendsDemo02 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		// 验证子类能否访问父类中的private属性或者方法
    		// 或者说继承?
    		child ch = new child();
    		ch.setage(10);
    		ch.name = "xiaomim";
    		System.out.println(ch);
    		System.out.println(ch.getage());
    
    	}
    
    }
    
    class person_private {
    	private int age;
    	String name;
    
    	public void setage(int age) {
    		this.age = age;
    	}
    
    	public int getage() {
    		System.out.println(this);
    		return this.age;
    	}
    
    }
    
    class child extends person_private {
    	void cry() {
    		System.out.println("wowo");
    	}
    }
    

    其运行结果如下:

    cn.haiyisoft3.child@55f33675
    cn.haiyisoft3.child@55f33675
    10
    
    这说明this和ch指向的是同一个对象,也就是说子类调用的自己实例对象内存空间的父类私有属性age。

    所以,我认为子类实例空间中是有父类的私有成员的,但是有不代表继承,只有能直接使用才说明子类继承了父类。

  • 相关阅读:
    小朋友排队--第五届蓝桥杯
    Spring IOC源代码具体解释之整体结构
    Libimseti推荐系统
    Codeforces Round #277.5 (Div. 2)(C题)
    数据库经常使用函数
    Command terminated by signal 11
    winform程序公布后,client下载报错“您的 Web 浏览器设置不同意执行未签名的应用程序”
    Cocos2d-x学习笔记(四) 布景层的加入移除
    FMSC 使用理解
    将浮点数保持几位小数,尾数舍入的Format函数
  • 原文地址:https://www.cnblogs.com/JSD1207ZX/p/9386236.html
Copyright © 2011-2022 走看看