Help to understand the issue with protected method

前端 未结 6 1224
野的像风
野的像风 2021-01-12 00:54

I\'m reading Sybex Complete Java 2 Certification Study Guide April 2005 (ISBN0782144195). This book is for java developers who wants to pass java certification.

6条回答
  •  情歌与酒
    2021-01-12 01:28

    That question seems badly worded - and asks about a very rare edge case (that I'm not even sure is covered on the SCJP test). The way that it's worded makes your answer correct and the given answer incorrect. Coding a similar construct and running it easily proves this...

    package inside;
    
    public class Base {
    
        private String name;
    
        public Base(String name)  {
            this.name = name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        protected String abby(String name) {
            String old = this.name;
            this.name = name;
            return old;
        }
    }
    
    
    
    
    package outside;
    import inside.Base;
    
    public class Another extends Base {
    
        public Another(String name) {
            super(name);
        }
    
        public String setAnother(Another another, String hack) {
            return another.abby(hack);
        }
    
        public static void doCrazyStuff() {
            Another one = new Another("one");
            Another two = new Another("two");
    
            one.abby("Hi one"); 
            two.abby("Hi two");
            one.setAnother(two, "Hi two from one");
    
            System.out.println("one = " + one.getName());
            System.out.println("two = " + two.getName());
    
        }
    
        public static void main(String[] args) {
            Another.doCrazyStuff();
        }
    }
    

提交回复
热议问题