开发者

scjp question on enum

开发者 https://www.devze.com 2023-02-23 04:29 出处:网络
public enum Scale2 { GOOD(\'C\') { public char getGrade() { return grade; } }, BETTER(\'B\') { public char getGrade() {
public enum Scale2 {

    GOOD('C') { 
        public char getGrade() { 
            return grade; 
        } 
    },
    BETTER('B') { 
        public char getGrade() { 
            return grade; 
        } 
    },
    BEST('A') { 
        public char getGrade() { 
            return grade; 
        } 
    };

    private char grade;

    Scale2(char grade) {
        this.grade = grade;
    }

    // (1) INSERT CODE HERE
    public char getGrade() { 
        return grade; 
    }

    开发者_开发百科public static void main (String[] args) {
        System.out.println(GOOD.getGrade());
    }
}

This is a program from khalid mughal scjp guid and following are the options and questions. When I tried to run this in eclipse, Its saying the non static grade cannot access from static context,I think according to concept its right,but I am confused wheather book is write or I am...please replay.

Which code, when inserted at (1), will make the program print C?

Select the two correct answers.

(a) public char getGrade() { return grade; }

(b) public int getGrade() { return grade; }

(c) abstract public int getGrade();

(d) abstract public char getGrade();


GOOD('C')
{ public char getGrade() { return grade; } },
BETTER('B') { public char getGrade() { return grade; } },
BEST('A')
{ public char getGrade() { return grade; } };
private char grade;

Problem with the sample code is that grade is declared as private. so grade is not accessible from its subclasses. Either grade should be accessible from its subclasses or subclasses of Scale2 should access grade through super.getGrade() method.

// (1) INSERT CODE HERE
public char getGrade() { return grade; } // inserted!

You have inserted the possibly correct code in your post, and yes, the book is wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消