Secret --java cloak inheritance / Hide / overwrite

story background

Read the "Harry Potter" baby who surely must remember the movie "invisibility cloak." . This is the Invisibility Cloak Harry received a Christmas gift, is one of the three-piece Hallows Death, it makes little friends Harry during the execution of the task is simply a menace!

Secret --java cloak inheritance / Hide / overwrite

 

In fact, plainly, it is wrapped in the cloak of human instinct and desire to control spy want, we desire to know and understand everything, but often do not want people to know, so we need to "cloak." .

 

Secret --java cloak inheritance / Hide / overwrite

 Inheritance Inheritance / hide hide / override override

java has inherited Inheritance / hide hide / override the concept overwritten Leave aside their differences, take a look at last little thing happened, boss wrong digit in a meeting, Leader said quickly: "That's my when mistaken "program ape to find Boss said the figure, but how is not OK, this is how it happened? See case playback:

public class Conference {
    public static void main(String[] args) {
        System.out.println(new Leader().sales);
    }
}
class Boss {
    public Integer sales=10000;
}
class Leader extends Boss{
    private Integer sales=9000;
}

At first glance, prints Leader 9000 sales data, but a closer analysis point of view, sales variables Leader class is private, the program can not compile. The program does not compile, but the error is in Conference class. Reason: the call is new new Conference Leader () Examples leader i.e., not Leader class, access to a method override access modifier is provided to be compared with access provided a method override access modifier, at least as much [JLS 8.4.8.3].

Because sales is a domain, so Leader.sales hidden (hide) the Boss.sales, instead of covering it [JLS 8.3]. For a domain, when it wants to hide another domain, if access hidden fields provide access modifier is less than the hidden field, even though doing so is not desirable, but it is indeed legal.

In fact, we can still find the boss said sales of. as follows:

public class Conference {
    public static void main(String[] args) {
        System.out.println(((Boss)new Leader()).sales);
    }
}
class Boss {
    public Integer sales=10000;
}
class Leader extends Boss{
    private Integer sales=9000;
}

to sum up

A very big difference between override and hide. Once a method is overwritten in a subclass, you can not call it on an instance of a subclass (except within the subclass method by using the super keyword). However, you can subclass instance by the transition to a superclass type of access to the hidden domain, in this superclass that domain is not hidden.

Reference material

[1] java doubts

【2】https://www.sohu.com/a/231064552_764920

Guess you like

Origin www.cnblogs.com/davidwang456/p/11696432.html