Docsity

Java Inheritance: Access Specifiers, Inheritance Relationship, and Data Members, Slides of Java Programming

Partial preview of the text

Download Java Inheritance: Access Specifiers, Inheritance Relationship, and Data Members and more Slides Java Programming in PDF only on Docsity!

Inheritance in Java

Access Specifiers

๏‚— private keyword ๏‚— Used for most instance variables ๏‚— private variables and methods are accessible only to methods of the class in which they are declared ๏‚— Declaring instance variables private is known as data hiding ๏‚— public keyword ๏‚— Exposes variables or methods outside the Class. ๏‚— Declaring public methods is know as defining the classโ€™ public interface. ๏‚— Protected keyword ๏‚— Provides limited access ๏‚— Provides access to sub classes but not to the classes outside a package

Inheritance

๏‚— Inheritance allows a software developer to reuse classes by

deriving a new class from an existing one

๏‚— The existing class is called the parent class, or superclass, or

base class

๏‚— The derived class is called the child class or subclass.

๏‚— As the name implies, the child inherits characteristics of the

parent

๏‚— That is, the child class inherits the methods and data defined

for the parent class

Inheritance Relationship

๏‚— Inheritance should create an is-a relationship , meaning the

child is a more specific version of the parent

Class Hierarchy

๏‚— Good class design puts all common features as high in the hierarchy as reasonable ๏‚— inheritance is transitive ๏‚— An instance of class Parrot is also an instance of Bird, an instance of Animal, โ€ฆ, and an instance of class Object

Class inheritance

๏‚— The inclusion of members of a base class in a derived class so that they are accessible in that derived class is called class inheritance. ๏‚— An inherited member of a base class is one that is accessible within the derived class. ๏‚— If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class.

Inheriting Data Members

Hidden Data Members

๏‚— Variables of same name both in base class and derived class ๏‚— Use of keyword super

Example

// A simple example of inheritance. // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } }

class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); //The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println();