朴素的继承问题 - Java [英] Naive Inheritance Problem - Java

查看:21
本文介绍了朴素的继承问题 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

G'day 的人们,

问这么幼稚的问题,我感到很尴尬.但我无法理解一件事,我有这样的继承结构,

I am feeling embarrass by asking such a naive question. But I can't understand one thing, I have Inheritance structure like this,

B扩展A,我写的代码如下,

B extends A, code I have wrote is as below,

A级

public class A{
    private int pos = 0;
    public A(){
        this.pos = 12;
    }
    public int getPos(){
        return this.pos;
    }
}

B级

public class B extends A{
    int spec = 15;
    public B(){
        super();
    }
    public int getSpec(){
        return this.spec;
    }
}

我还有一门课要测试,这会让我们回答我的问题.

And I have one more class to test, Which will get us to my question.

课堂测试

import java.util.*;
public class Test{
    public static void main(String[] args){
        B a = new B();
        ArrayList<A> c = new ArrayList<A>();
        c.add(a);
        System.out.println(c.get(0).getPos());
        System.out.println(c.get(0).getSpec());
    }
}

问题:现在我正在创建 B 的一个实例,这意味着我可以访问我父类的方法 getPos() 和 B 自己的方法 getSpec().但是,如果我创建类型为 A(...B 也是类型 A,因为它扩展 A...) 的 ArrayList 并添加我的 B 的实例,它会失去访问它自己的方法的能力.我究竟做错了什么?ArrayList 实现是否在内部将我的 B 转换为 A?

Question : Now I am creating an instance of B, Which means I can access to my parent class's method getPos() and B's own method getSpec(). But if I create ArrayList with type A(...B is type A too, as it extends A...) and add my B's instance it losses it's ability to access it's own method. What am I doing wrong? Does ArrayList implementation is casting my B to A internally?

注意:我对继承的基本理解是父级不能访问孩子的方法,除非他们受到保护.但是孩子可以访问他们的父类的方法.

Note : My basic understanding of inheritance is parent cannot access child's method except they are protected. But Child can access their parent class's method.

推荐答案

除了 @Matt Ball@Hovercraft 满是鳗鱼,您可以通过将子类实现的方法声明为抽象<超类中的/strong> 方法.

In addition to the answers provided by @Matt Ball and @Hovercraft Full Of Eels, you can avoid having to explicitly cast by declaring methods implemented by the subclass as abstract methods in the superclass.

public abstract class A{
    .
    .
    public abstract int getSpec();
}

<小时>

编辑-

正如@Kublai Khan 所提到的,有必要创建超类 一个抽象类.

As mentioned by @Kublai Khan, it is necessary to then make the superclass an abstract class.

这篇关于朴素的继承问题 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆