2013-03-16 47 views
5

子类对象如何引用超类?例如:继承:从子类访问基类字段

public class ParentClass { 

    public ParentClass() {}  // No-arg constructor. 

    protected String strField; 
    private int intField; 
    private byte byteField; 
} 


public class ChildClass extends ParentClass{ 

    // It should have the parent fields. 
} 

这里当ChildClass构造函数被调用,创建ParentClass类型的对象,对不对?

ChildClass从ParentClass对象继承strField,所以它(ChildClass对象)应该有权访问ParentClass对象,但是怎么做?

+0

使用super关键字:P – Sach 2013-03-16 17:44:36

+0

这是非常糟糕的称号。考虑在那里放一些背景。 – Nishant 2013-03-16 17:46:20

+0

我同意,(:-)现在更好! – 2013-03-16 19:21:41

回答

5

当你做ChildClass childClassInstance = new ChildClass()时,只有一个新的对象被创建。

可以看到ChildClass由定义的对象:

  • 从父类ChildClass +字段的字段。

等等领域strField是ChildClass的一部分,可以通过childClassInstance.strField

所以你的假设

ChildClass的构造函数被调用类型的父类的一个对象被创建访问

不完全正确。创建的childClass实例也是一个ParentClass实例,它是同一个对象。

1

您可以访问strField,就好像它在ChildClass中声明一样。为避免混淆,您可以添加super.strField这意味着您正在访问父类中的字段。

4

ChildClass实例没有一个ParentClass对象,它一个ParentClass对象。作为一个子类,它可以访问其父类中的公共和受保护的属性/方法。所以这里ChildClass有权访问strField,但不是intFieldbyteField,因为它们是私人的。

您可以在没有任何特定语法的情况下使用它。

1

是的。您将能够访问ChildClass中的strField,而不执行任何特殊操作(但请注意,只有一个实例将被创建。子项将从父项继承所有属性和方法)。

1

这里当ChildClass的构造函数被调用类型为 的对象时,是否创建了父类?

不!ChildClass的构造函数被调用>>父类的构造函数被调用 和父类的对象不从父类创建只是接近场均继承了ChildClass

的ChildClass继承了父类对象strField,所以它 ( ChildClass对象)应该有权访问ParentClass对象,但是如何?

不,它只是重用父类的模板来创建新的ChildClass

0

只针对无参构造函数,编译器的介入的业务,而派生类(ChildClass)的默认构造函数(非参数构造函数)被调用时,基类(ParentClass)的子对象通过编译器的帮助机制(在派生类中插入基类构造函数调用)创建并包装在派生类的对象中。

class Parent{ 
    String str = "i_am_parent"; 
    int i = 1; 
    Parent(){System.out.println("Parent()");} 
} 
class Child extends Parent{ 
    String str = "i_am_child"; 
    int i = 2; 
    Child(){System.out.println("Child()");} 
    void info(){ 
     System.out.println("Child: [String:" + str + 
          ", Int: " + i+ "]"); 
     System.out.println("Parent: [String: ]" + super.str + 
          ", Int: " + super.i + "]"); 
    } 
    String getParentString(){ return super.str;} 
    int getParentInt(){ return super.i;} 
    public static void main(String[] args){ 
     Child child = new Child(); 
     System.out.println("object && subojbect"); 
     child.info(); 
     System.out.println("subojbect read access"); 
     System.out.println(child.getParentString()); 
     System.out.println(child.getParentInt()); 

    } 
} 

结果:

Parent() 
Child() 
object && subojbect 
Child: [String:i_am_child, Int: 2] 
Parent: [String: ]i_am_parent, Int: 1] 
subojbect read access 
i_am_parent 
1