小编Jac*_*ack的帖子

Java继承 - 此关键字

我在网上搜索了类似的问题,但找不到它.所以,发布在这里.

在以下程序中,为什么'i'的值打印为100?

AFAIK'this'指的是当前的对象; 在这种情况下,它是'TestChild',类名也正确打印.但为什么实例变量的值不是200?

public class TestParentChild {
    public static void main(String[] args) {
        new TestChild().printName();
    }
}

class TestChild extends TestParent{
    public int i = 200;
}

class TestParent{
    public int i = 100;
    public void printName(){
        System.err.println(this.getClass().getName());
        System.err.println(this.i); //Shouldn't this print 200
    }
}
Run Code Online (Sandbox Code Playgroud)

而且以下的输出正如我预期的那样.当我从Parent类调用" this.test() " 时,将调用子类方法.

public class TestParentChild {
    public static void main(String[] args) {
        new TestChild().printName();
    }
}

class TestChild extends TestParent{
    public int i = 200;
    public void test(){
        System.err.println("Child Class : "+i); …
Run Code Online (Sandbox Code Playgroud)

java inheritance overriding this

5
推荐指数
1
解决办法
871
查看次数

Java - 通用类型 - 类型擦除

我在oracle网站上找到了以下问题和答案

类型擦除后,以下类转换为什么?

public class Pair<K, V> {

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey(); { return key; }
    public V getValue(); { return value; }

    public void setKey(K key)     { this.key = key; }
    public void setValue(V value) { this.value = value; }

    private K key;
    private V value;
}
Run Code Online (Sandbox Code Playgroud)

回答:

public class Pair {

    public Pair(Object key, Object value) {
        this.key = key;
        this.value = value;
    }

    public Object getKey() …
Run Code Online (Sandbox Code Playgroud)

java generics

4
推荐指数
1
解决办法
683
查看次数

标签 统计

java ×2

generics ×1

inheritance ×1

overriding ×1

this ×1