Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

java - Simple inheritance but confusing

This is class JavaTest

package testing.test;

public class JavaTest 
{
    int i=2;
}

This is class JavaTest2 , which extends JavaTest

package testing.test;

class JavaTest2 extends JavaTest
{
    public static void main(String[] args) {


        new JavaTest2().add(5);
    }

    void add(int i)
    {
        System.out.println(5+i);
    }
}

Now the output is coming to 10 , actual problem is get the i value of parent class to add..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The thing here is that your add method shadows the i attribute of the class with the i variable declared as parameter. Thus, when using i inside add method, you're using the i parameter, not the i attribute.

To note the difference, change the add method to:

void add(int i) {
    System.out.println(5+i);
    System.out.println(5+this.i); //this will do the work for you
}

A good example of shadowing is used on class constructors:

public class SomeClass {
    int x;
    public SomeClass(int x) {
        //this.x refers to the x attribute
        //plain x refers to x parameter
        this.x = x;
    }
}

Follow up from comment:

got it , but what happens if i have the same member as i in JavaTest2 ...and do the same this.i

This is called hiding and is well explained in Oracle's Java tutorial: Hiding Fields

Example:

class JavaTest2 extends JavaTest {
    int i = 10;
    void add(int i) {
        System.out.println(5+i);
        System.out.println(5+this.i); //this will add 5 to i attribute in JavaTest2
        System.out.println(5+super.i); //this will add 5 to i attribute in JavaTest
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...