Creating References Using Inheritance Hierarchies

Creating References Using Inheritance Hierarchies

Understanding Inheritance Hierarchies

  • An inheritance hierarchy is a group of classes related by inheritance, where a subclass inherits from a superclass.
  • In Java, the Object class stands at the top of every inheritance hierarchy, implicitly inheriting to every other class.

Creating References

  • Object references can point to instances of their class or subclasses. For example, if Cat is a subclass of Animal, an Animal reference can refer to a Cat object.
  • Declaring a variable of a superclass type and assigning it an instance of a subclass is known as upcasting. This is automatic as every subclass object is an instance of its superclass.
  • References and objects are not the same. References can be changed to refer to different objects and null can be assigned to references.

Assigning and Accessing References

  • When a subclass object is assigned to a superclass reference, only the methods and variables accessible from the superclass type are callable directly from the reference.
  • However, if these methods are overridden in the subclass, the subclass versions will be called.
  • Any methods or variables only found in the subclass are inaccessible directly from a superclass reference. To access these, downcasting must be done explicitly.
  • Downcasting is the conversion of a reference from a superclass type to a subclass type. It can lead to ClassCastException if not handled carefully.

Overriding and Overloading

  • Overriding occurs when a subclass provides a method that has the same name and parameter types as a method in its superclass.
  • The overriding method in the subclass has to have the same (or less restrictive) visibility as the superclass method and it can’t throw more exceptions than the super class method does.
  • Unlike overriding, overloading occurs when there are two or more methods with the same name but different parameter lists in the same class.

Polymorphism

  • Polymorphism is an Object Oriented Programming principle that allows us to perform a single action in different ways. It allows references to behave differently based on the type of object they are pointing to.
  • Method overloading and method overriding are two forms of Polymorphism.
  • The JVM determines the correct method to call at runtime, which is referred to as dynamic method dispatch or runtime polymorphism.

Importance of InstanceOf Operator

  • The instanceof operator checks whether an object is an instance of a specified class or implements a specified interface.
  • It’s used primarily for type comparison and downcasting.
  • It helps prevent a ClassCastException in downcasting by checking if a conversion is valid before attempting it.