`

java中super关键字的作用和用法

 
阅读更多

 

   super用于在 派生类中调用父类的重名方法,或者引用重名的变量。

 

    super被用在派生类中,就是为了明确调用父类的方法。

 

 

示例(很浅显易懂):

 

      FROM: http://stackoverflow.com/questions/3767365/super-in-java

 

-------------------------------------------------

1.Super keyword is used to call immediate parent.

2.Super keyword can be used with instance members i.e., instance variables and instance methods.

3.Super keyword can be used within constructor to call the constructor of parent class.

OK now let’s practically implement this points of super keyword.

Check out the difference between program 1 and 2. Here program 2 proofs our first statement of Super keyword in Java.

Program 1

class base
{
    int a = 100;
}

class sup1 extends base
{
    int a = 200;
    void show()
    {
        System.out.println(a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new sup1().show();
    }
}

Output : -

200

200

Now check out the program 2 and try to figure out the main difference.

Program 2

class base
{
    int a = 100;
}

class sup2 extends base
{
    int a = 200;
    void show()
    {
        System.out.println(super.a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new sup2().show();
    }
}

Output

100

200

In the program 1, the output was only of the derived class. It couldn’t print the variable of base class or parent class. But in the program 2, we used a super keyword with the variable a while printing its output and instead of printing the value of variable a of derived, it printed the value of variable a of base class. So it proofs that Super keyword is used to call immediate parent.

OK now check out the difference between program 3 and program 4

Program 3

class base
{
    int a = 100;
    void show()
    {
        System.out.println(a);
    }
}

class sup3 extends base
{
    int a = 200;
    void show()
    {
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new sup3().show();
    }
}

Output

200

Here the output is 200. When we called the show function, the show function of derived class was called. But what should we do if we want to call the show function of the parent class. Check out the program 4 for solution.

Program 4

class base
{
    int a = 100;
    void show()
    {
        System.out.println(a);
    }
}

class sup4 extends base
{
    int a = 200;
    void show()
    {
        super.show();
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new sup4().show();
    }
}

Output

100

200

Here we are getting two output 100 and 200. When the show function of derived class is invoke, it first calls the show function of parent class because inside the show function of derived class we called the show function of parent class by putting the super keyword before the function name.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics