Java Reference
In-Depth Information
Making base class members protected allows them to be accessed from other classes in the
same package, but prevents direct access from a class in another package. Base class members
that are protected are inherited in a subclass and can, therefore, be used in the
implementation of a derived class. You can use the protected option when you have a
package of classes in which you want uninhibited access to the data members of any class
within the same package, because they operate in a closely coupled way, for instance, but you
want free access to be limited to subclasses in other packages.
Omitting the access attribute for a class member makes it directly available to other classes in
the same package, while preventing it from being inherited in a subclass that is not in the
same package - it is effectively private when viewed from another package.
Polymorphism
Class inheritance is not just about reusing classes that you have already defined as a basis for defining a
new class. It also adds enormous flexibility to the way in which you can program your applications, with
a mechanism called polymorphism . So what is polymorphism?
The word 'polymorphism' generally means the ability to assume several different forms or shapes. In
programming terms it means the ability of a single variable of a given type to be used to reference
objects of different types, and to automatically call the method that is specific to the type of object the
variable references. This enables a single method call to behave differently, depending on the type of
the object to which the call applies.
Dog aDog; //Variable to hold any kind of dog object
Dog
bark()
Spaniel
Chihuahua
Collie
bark()
bark()
bark()
Call any of these methods depending on the object type
aDog.bark()
The variable aDog can be used to refer to an object of the
base class type, or an object of any of the derived class types.
There are a few requirements that need to be fulfilled to get polymorphic behavior, so let's step
through them.
Search WWH ::




Custom Search