0

Im trying to declare a protected variable inside a protected class but get an error,

protected class Car {
    protected int x = 9;
}

The valid modifier for the class is public, abstract and final as per Eclipse.

Can someone please explain?

user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 1
    If `Car` is a top-level class, it doesn't make any sense to make it `protected`. `Protected` members of a class are things that are visible to that class and to subclasses. But a top-level class isn't a member of any other class. – ajb Jan 24 '14 at 01:01
  • Maybe it would help if you explain what you think a "protected class" is, and why you want `Car` to be that. Then we might be able to figure out what you really want. – ajb Jan 24 '14 at 01:04

1 Answers1

0

A class (or interface) cannot be protected, only fields and methods within a class can be. However, there is an exception where if you have nested (or inner) classes or interfaces you can in fact label them as protected. I am assuming that your class is a top level class though, hence why you are receiving an error message.

JNYRanger
  • 6,829
  • 12
  • 53
  • 81
  • Clarification: A class declared within another class (nested or inner class) **can** be protected. So can a nested interface. The tutorial is not quite accurate here. – ajb Jan 24 '14 at 01:07
  • True, I probably shouldn't have assumed it wasn't a nested class (or interface) I was just looking for a reference for OP and saw that since Oracle's tutorials doesn't really explain what you can't do in that aspect. I'll update the answer – JNYRanger Jan 24 '14 at 01:09