GeeCON Prague 2014*
The moose likes Java in General and the fly likes Modifiers Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Modifiers Question" Watch "Modifiers Question" New topic
Author

Modifiers Question

Mike Cutter
Ranch Hand

Joined: Jun 09, 2002
Posts: 49
In the following code:



Do the six modifiers satisfy the following requirements?

1. It must be possible to create instances of Alpha and Beta from outside the packages in which they are defined.
2. When an object of type Alpha (or any potential subclass of Alpha) has been created, the instance variable alpha may never be changed.
3. The value of the instance variable alpha must always be "A" for objects of type Alpha.

The above code was the only combination of private, protected, and public modifiers that I can get compiled. By using the public modifier, I was unsure if the code satisfied the requirements?

Any insight would be helpful.

Thanks,

Mike
Costa lamona
Ranch Hand

Joined: Sep 24, 2006
Posts: 102
1. It must be possible to create instances of Alpha and Beta from outside the packages in which they are defined.

Yes, public classes can be instantiated from outside the packages in which they are defined.

2. When an object of type Alpha (or any potential subclass of Alpha) has been created, the instance variable alpha may never be changed.

protected access modifier is avoiding outside world from access and change alpha, but every class extend alpha outside the package alpha, or any class inside package alpha can access alpha reference.

Remmeber that, although String object is immutable by its nature, String ref is not.

But to realy make alpha immutable make it final, so the answer is No.

3. The value of the instance variable alpha must always be "A" for objects of type Alpha

If you mean only Alpha, and not its subclasses too then,
You did not satisfy that in any way,

public Alpha(String a) { alpha = a; }
You should remove this

if you still need it use this constructor
see Object.getClass()
Class.getName()

I don't know why you make default constructor Alpha() not public !!

Remember that superclass constructor is first called before subclasses
constructors as a result to super() or super(...) keyword, if you did not write super(), compiler will write it for you, if compiler did not find matching constructor to super(), the code will not compile.
Compiler donot add a default constructor except if you did not provide any constructors. compiler donot write super(...), it write super() only.

I hope this is helpful.


SCJP 5
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Modifiers Question