我很难绕过这种奇怪的Java继承行为。
说,我有 Parent 类,私有方法 method1 。然后是一个扩展 Parent 类的 Child 类。 Child 还定义了名为 method1 的方法,但它是公共的。请参阅下面的例子:
public class Main {
public static void main(String[] args) {
Parent p = new Child();
p.method2();
}
}
class Parent{
private void method1() {
System.out.println ( "Parent's method1()" );
}
public void method2() {
System.out.println ( "Parent's method2()" );
method1();
}
}
class Child extends Parent {
public void method1() {
System.out.println ( "Child's method1()" );
}
}
我不明白的是输出低于!!!
Parent's method2()
Parent's method1()
我知道由于 method1 在 Parent 中是私有的, Child 中的 method1 与此无关父母。如果是这样,那么当 method2 调用 method1 时,为什么 Parent 的 method1 被调用而不是 Child 的?特别是当实际类型是 Child 时。
似乎完全没有线索从 method2 调用 method1 。 我错过了继承规则吗?请帮忙!!!
答案 0 :(得分:2)
private void method1()
阻止该方法被覆盖。
因此,任何子类都不能继承此method1()
在您的代码中,子类有自己独立的method1()
。
Parent p = new Child(); // We have p of Parent reference and is a Child object
p.method2(); // At compile time this statement binds the method2() from Parent class
由于只有父类有method2()
,所以它被称为。
但是,假设您在Child类中重写了此方法。
class Child extends Parent {
public void method1() {
System.out.println("Child's method1()");
}
public void method2() {
System.out.println("Child's method2()");
}
}
在这种情况下,即使在编译时,method2()
也绑定到父类
但是在运行时,会调用Child类的method2()
。这是运行时多态性。
因此,呼叫p.method2()
的输出将是
Child's method2()
Child's method1()
答案 1 :(得分:1)
protected
方法和字段未继承。 protected void method1() {
System.out.println ( "Parent's method1()" );
}
是您正在考虑的访问修饰符。在您的帖子中,方法没有关系(除了具有相同的名称)。
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>