310 035 ObjectOrientedConcepts
310 035 ObjectOrientedConcepts
Object Oriented
Concepts
-2-
If no extends clause is specified in the header of a class declaration, then the class
implicitly inherits from the java.lang.Object class. Thats the top-most class in an
inheritance hierarchy chain [super1 • super2 • super3 • sub]
Private members of the superclass are not inherited by the subclass and can only be
indirectly accessed. but exists in the subclass object and is indirectly accessible.
the subclass can use other inherited members as if they were declared in its own class
body. (by simple name or this)
Members that have package accessibility in the superclass are also not inherited by
subclasses in other packages. These members are only accessible by their simple
names in subclasses within the same package as the superclass.
Since constructors and initializer blocks are not members of a class, they are not
inherited by a subclass.
Inheritance defines "is-a" Relationship between subClass and superClass. This means
that an object of a subclass can be used wherever an object of the superclass can be
used. (As SuperClass is a SubClass) TubeLight is a Light.
Casting:
Reference of one type is Casted into another type
Upcasting
Subclass reference is assigned to superClass reference. As an object of subclass can
be used wherever an objet of super can be used.
Object objRef = stringRef;
Both references denote the same string object.
Its not possible to invoke methods exclusive to the subclass, String via the superclass
reference objRef:
objRef.length()would be flagged as a compile-time error.
as the compiler only knows the class of the reference. It does not know what object the
reference objRef is denoting.As the declaration of the Object class does not have a
method length(), invocation of length() using objRef with flag a compile-time error.
Downcasting
Superclass reference is assigned to a subclass type.
-3-
by assigning references down the inheritance hierarchy, which requires explicit casting.
widen it.
3. The new method definition can only specify all or none, or a subset of the exception
classes (including their subclasses) specified in the throws clause of the overridden
method in the superclass.
The sub-class overriding method doesn't throw any exception, what if, Super-Class one
can have an ability to throw an exception.
Interfaces:
These requirements also apply to interfaces, where a subinterface can override method
prototypes from its superinterfaces
class Light {
protected String billType = "Small bill"; // (1)
:
:
TubeLight tubeLight = new TubeLight(); // (9)
Light light1 = tubeLight; // (10)
Aliases.
Light light2 = new Light(); // (11)
A subclass must use the keyword super in order to invoke an overridden method in the
superclass.
A final method cannot be overridden because the modifier final prevents method
overriding. An attempt to override a final method will result in a compile-time error.
A final field in the Super class can be hidden in the sub-class.
-6-
Private methods are not inherited. The method is not accessible outside the class in
which it is defined; therefore, a subclass cannot override it. A subclass can give its own
definition of such a method, which may have the same signature as the method in its
superclass.
Method Hiding:
Static(super)~Static(sub) Method Hiding:
A static method in a subclass can hide a static method in the superclass if the exact
requirements for overriding instance methods are fulfilled. A hidden superclass static
method is not inherited. The compiler will flag an error if the signatures are the same but
the other requirements regarding return type, throws clause, and accessibility are not
met.
If the signatures are different, the method name is overloaded, not hidden.
Field Hiding:
The subclass can define fields with the same name as in the superclass. ⇒ the fields in
the superclass cannot be accessed in the subclass by their simple names; therefore,
they are not inherited by the subclass.
Code in the subclass can use the keyword super to access such members, including
hidden fields.
A client can use a reference of the superclass to access members that are hidden in the
subclass.
Static field can be hidden by non-static field. NO Restrictions like the static Methods <<
As fields have compile time binding >> the reference determine which on is to be called
<< no concept of polymorphism
A hidden static method can be invoked by using the superclass name in the subclass
declaration. The keyword super can be used in non-static code in the subclass
declaration to invoke hidden static methods
-7-
Overloading:
when the method names are the same, but different signature.
to overload methods the parameters must differ in type, order, or number. As the return
type is not a part of the signature, having different return types is not enough to overload
methods.
A method can be overloaded in the class it is defined in or in a subclass of its class.
Invoking an overridden method in the superclass from a subclass requires special syntax
(e.g., the keyword super). This is not necessary for invoking an overloaded method in the
superclass from a subclass. If the right kinds of arguments are passed in the method call
occurring in the subclass, the overloaded method in the superclass will be invoked.
Method Overloading Resolution : how parameter resolution is done to choose the right
implementation for an overloaded method?
The most specific method is chosen.
satisfies the parameter lists in both the implementations given at (1) and (2), as the
reference tubeLight, which denotes an object of class TubeLight, can also be assigned to
a reference of its superclass Light. The most specific method, (2), is chosen.
class Light {
super.banner(); // (10)
Invokes method at (4)
super.getBill(); // (11)
Invokes method at (8)
super.getBill(20); // (12)
Invokes method at (6)
((Light) this).getBill(20); // (13)
Invokes method at (6)
System.out.println(super.billType); // (14)
Accesses field at (5)
System.out.println(((Light) this).billType); // (15)
Accesses field at (1)
super.printBillType(); // (16)
Invokes method at (7)
((Light) this).printBillType(); // (17)
Invokes method at (3)
//Static Method
}
}
Wrong Use:
super.super.doIt();
this.super.doIt();
super and this aren't part of the class, they are not inherited by a subclass.
super isn't a part of the class, so can't be accessed using this keyworld.
super and this are keywords, aren't part of the class.
-9-
object.super.msg.text
.super() << to bind an Inner Class with the other class object <<Special pattern
Compilation error
class Light {
// Fields
/*...*/
// Constructors
Light() { // (1) Explicit
default constructor
this(0, false);
System.out.println("Returning from default constructor
no. 1.");
}
Light(int watt, boolean ind) { // (2) Non-default
this(watt, ind, "X");
System.out.println("Returning from non-default
constructor no. 2.");
}
Light(int noOfWatts, boolean indicator, String location)
{ // (3) Non-default
System.out.println("Returning from non-default
constructor no. 3.");
}
}
super() Constructor Call >> Vertical Chaining >> chaining of subclass constructors to
superclass constructors.
used in a subclass constructor to invoke a constructor in the immediate superclass
(based on the signature of the call). This allows the subclass to influence the initialization
of its inherited state when an object of the subclass is created.
[super keyword can be used in a subclass constructor to access inherited/hidden
members via its superclass.]
The super() construct has the same restrictions as the this() construct:
if used, the super() call must occur as the first statement in a constructor, and
it can only be used in a constructor declaration. This implies that this() and super() calls
cannot both occur in the same constructor.
If a constructor has neither a this() nor a super() call as its first statement, then a super()
call to the default constructor in the superclass is inserted implicitly.
This chaining behavior guarantees that all superclass constructors are called, starting
with the constructor of the class being instantiated, all the way to the top of the
inheritance hierarchy, which is always the Object class.
The body of the constructors is executed in the reverse order to the call order, as super()
- 11 -
can only occur as the first statement in a constructor. This ensures that the constructor
from the Object class is completed first, followed by the constructors in the other classes
down to the class being instantiated in the inheritance hierarchy.
If a class only defines non-default constructors, then its subclasses cannot rely on the
implicit super() call being inserted. This will be flagged as a compile-time error. The
subclasses must then explicitly call a superclass constructor, using the super() construct
with the right arguments.
Subclass() { // (1)
super(10, 2); // (2) Cannot be commented out. As nO
default one in MUST
superClass
/*...*/
}
// ...
}
- 12 -
Interface:
<accessibility modifier> interface <interface name>
<extends interface clause> //
Interface header
{ // Interface body
<constant declarations>
<method prototype declarations>
<nested class declarations>
<nested interface declarations>
}
Implementing Interfaces:
The criteria for overriding methods also apply when implementing interface methods.
The interface methods must all have public accessibility when implemented in the class
(or its subclasses). A class can neither narrow the accessibility of an interface method
nor specify new exceptions in the method's throws clause, as attempting to do so would
amount to altering the interface's contract, which is illegal.
Interface methods are always implemented as instance methods.
A class can choose to implement only some of the methods of its interfaces, . The class
must then be declared as abstract.
Extending Interfaces
An interface can extend other interfaces, using the extends clause.
Unlike extending classes, an interface can extend several interfaces.
interface Int2 extends Int1, Int{ /*...*/}
A subinterface inherits all methods from its superinterfaces, as their method declarations
are all implicitly public. A subinterface can override method prototype declarations from
its superinterfaces. Overridden methods are not inherited. Method prototype declarations
can also be overloaded, analogous to method overloading in classes.
Constants in Interfaces
An interface can also define named constants. Such constants are defined by field
declarations and are considered to be public, static and final. These modifiers can be
omitted from the declaration.
Such a constant MUST be initialized with an initializer expression.
An interface constant can be accessed by any client (a class or interface) using its fully
qualified name, regardless of whether the client extends or implements its interface.
However, if a client is a class that implements this interface or an interface that extends
this interface, then the client can also access such constants directly without using the
fully qualified name. Such a client inherits the interface constants.
Extending an interface that has constants is analogous to extending a class having static
variables.
these constants can be hidden by the subinterfaces.
In the case of multiple inheritance of interface constants, any name conflicts can be
resolved using fully qualified names for the constants involved.
We can create an array of an interface type, but we cannot instantiate an interface (as is
the case with abstract classes).
Sup[] iSupArray = new Sup[5]; // Array of Interface
//The array creation expression creates an array whose element type is ISup.
An array reference exhibits polymorphic behavior like any other reference.
-->
SuperClsArray[0] = new SuperCls(); // ArrayStoreException ç SuperClsArray[0] is a
reference of type SubCls
Compile Time - no problems, As compiler cannot deduce that the array variable
SuperClsArray will actually denote an SubCls[] object at runtime. ç
For values of the primitive data types and reference types, conversions can occur during
• assignment
• parameter passing
• explicit casting
The rule of thumb for the primitive data types is that widening conversions are permitted,
but narrowing conversions require an explicit cast.
The rule of thumb for reference values is that conversions up the type hierarchy are
permitted (upcasting), but conversions down the hierarchy require explicit casting (
downcasting).
subtype to its supertypes are allowed, other conversions require an explicit cast or are
illegal.
If an assignment is legal, then the reference value of srcRef is said to be assignable (or
assignment compatible) to the reference of DestinationType.
The rules for assignment are enforced at compile time, guaranteeing that no type
conversion error will occur during assignment at runtime. Such conversions are type
safe. The reason the rules can be enforced at compile time is that they concern the type
of the reference (which is always known at compile time) rather than the actual type of
the object being referenced (which is known at runtime).
The rules are -
1. If SourceType is a class type, then the reference value in srcRef may be assigned to
the destRef reference, provided DestinationType is one of the following:
o DestinationType is a superclass of the subclass SourceType.
o DestinationType is an interface type that is implemented by the class
SourceType.
objRef = subClassRef; // (1) Always possible
superClassRef = subClassRef; // (2) Subclass to superclass assignment
iSuperTypeRef = superClassRef; // (3) SuperClass implements
IntefacesSuperType
iSubTypeRef = subClassRef; // (4) SubClass implements
InterfaceSubType
2. If SourceType is an interface type, then the reference value in srcRef may be
assigned to the destRef reference, provided DestinationType is one of the following:
o DestinationType is Object.
o DestinationType is a superinterface of subinterface SourceType.
objRef = iSubTypeRef; // (5) Always possible
iSuperTypeRef = iSubTypeRef; // (6) Subinterface to superinterface
assignment
3. If SourceType is an array type, then the reference value in srcRef may be assigned to
the destRef reference, provided DestinationType is one of the following:
o DestinationType is Object.
o DestinationType is an array type, where the element type of SourceType is
assignable to the element type of DestinationType.
objRef = objArray; // (7) Always possible Object[] to
Object
- 16 -
checks that the reference value of the object denoted by the <reference> is assignable to
a reference of the <destination type>,--> <source type> is compatible to the <destination
type>. If this is not the case, a ClassCastException is thrown.
The binary instanceof operator has the following syntax (note that the keyword is
composed of only lowercase letters):
<reference> instanceof <destination type>
The instanceof operator returns true if the left-hand operand (<reference>) can be cast
to the right-hand operand (<destination type>).
Always returns false if the left-hand operand is null.
(null instanceof Object) // Always false.
If the instanceof operator returns true, then the corresponding cast expression will
always be valid.
Both the cast and the instanceof operators require a compile-time check and a runtime
check:
The compile-time check determines
whether <source type> and <destination type> are in the type hierarchy.
[<source type> and <destination type> reference type can denote objects of a reference
type that is a common subtype of both <source type> and <destination type> in the type
hierarchy.]
If this is not the case, then obviously there is no relationship between the types, and
neither the cast nor the instanceof operator application would be valid.
The runtime check -
it is the type of the actual object denoted by the <reference> that determines the
outcome of the operation.
<source Object type> assignable to <destination type>
<source Object type> is subType of <destination type> in the type hierarchy .
- 17 -
if Not Assignable -
instanceof -> false
casting -> ClassCastException
Interfaces are constructs which do not contain any implementation. Interfaces only enforce a
nature of behavior.
The real advantage offered by interfaces is that of poly-morphism. It is the ability to use an
implementation via the interface's/supertype's reference. This offers real power because it offers
the facility to plug and play with multiple versions of implementations.
- 20 -
No compiler error - the class cannot be instantiated directly. It has to be extended to an non-
abstract class.
The constructors of the extended class will call the constructor of the abstract class (implicitly
or explicitly).