0% found this document useful (0 votes)
23 views

Lecture 5 Inheritance Constructor Chaining Access Modifiers and Object Class

The document discusses inheritance in Java and its key features like constructor chaining, overriding methods and variables, and using the super keyword. It explains how inheritance allows classes to extend existing classes to reuse their properties and behaviors, and how subclasses inherit variables and methods from superclasses unless access is restricted.

Uploaded by

biswa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Lecture 5 Inheritance Constructor Chaining Access Modifiers and Object Class

The document discusses inheritance in Java and its key features like constructor chaining, overriding methods and variables, and using the super keyword. It explains how inheritance allows classes to extend existing classes to reuse their properties and behaviors, and how subclasses inherit variables and methods from superclasses unless access is restricted.

Uploaded by

biswa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lecture 5

Outcome of the Lecture

Upon completion of this lecture you will be able to

✓ Use the features of inheritance in programs

✓ Understand constructor chaining and super keyword

✓ Control the access of class data members

✓ Understand Object class


Outline of the Presentation

✓ Inheritance

✓ Variables and Method Overriding

✓ Constructor Chaining

✓ super Keyword

✓ Object class and its methods

✓ Access modifiers and scope of a variable


Inheritance

Different classes may have some common properties and behaviors, which can
be generalized in a class that can be shared by other classes. Inheritance enables
you to define a general class and later extend it to more specialized classes.

Inheritance is

✓ Deriving new classes from existing classes

✓ powerful feature in Java for reusing software

✓ Every class in Java is inherited from an existing class either explicitly (extends)
or implicitly (Object class)
✓ is a relationship
Inheritance

✓ A class C1 extended from another class C2, is called sub class and C2
is called super class
✓ Super class or base class or parent class
✓ Sub class or child class or derived class or extended class
class SuperClass { class SubClass extends SuperClass{
int i=10; int k=20;
void showi() { void showk() {
System.out.println("i " + i); System.out.println(" k " + k);
} }
} }
SuperClass SubClass
Class Members
Class Members
k and showk()
i and showi() Inherited Members

i and showi()
Inheritance

public class DemoClass {


public static void main(String[] args){
SubClass sc = new SubClass();
sc.showi();
sc.showk();
}
}
class SimpleInheritance {
Inheritance
public static void main(String args[]) {

// Another simple example of inheritance. A superOb = new A();


B subOb = new B();
// Create a superclass.
// The superclass may be used by itself.
class A {
superOb.i = 10;
int i, j;
superOb.j = 20;
void showij() {
System.out.println("Contents of superOb: ");
System.out.println("i and j: " + i + " " + j);
superOb.showij();
}} /* The subclass has access to all public
// Create a subclass by extending class A. members of

class B extends A { its superclass. */


subOb.i = 7;
int k;
subOb.j = 8;
void showk() {
subOb.k = 9;
System.out.println("k: " + k);
System.out.println("Contents of subOb: ");
}
subOb.showij();
void sum() {
subOb.showk();
System.out.println("i+j+k: " + (i+j+k)); System.out.println();
} System.out.println("Sum of i, j and k in
Member Access & Inheritance
// Create a superclass. class Access {
class A { public static void main(String args[]) {
int i; // public by default B subOb = new B();
private int j; // private to A subOb.setij(10, 12);
void setij(int x, int y) { subOb.sum();
i = x; System.out.println("Total is " + subOb.total);
j = y; }
} }
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
Constructor Chaining

Are superclass’s Constructor Inherited?

✓ No
✓ They are invoked explicitly (Super keyword) or implicitly (constructor
chaining)

Constructor Chaining

✓ Constructing an instance of a class invokes all the superclasses’ no


argument constructors along the inheritance chain.
✓ Parameterized constructors are not invoked in a chain implicitly (can be
invoked with the use of super())
Constructor Chaining

class A{
public A(){
System.out.println("In A");
}
}
class B extends A{
public B(){
System.out.println("In B");
}
}
class C extends B{
public C(){
System.out.println("In C");
}
}
public class CC{
public static void main(String[] a){
C ob = new C();
}
}
Super keyword

✓ A superclass's constructors are not inherited in the subclass.


✓ They can only be invoked from the subclasses' constructors, using the keyword super.
✓ If the keyword super is not explicitly used, the superclass's no-arg constructor is
automatically invoked. (as demonstrated in last slide)
✓ A constructor may invoke an overloaded constructor or its superclass’s constructor. If
none of them is invoked explicitly, the compiler puts super() as the first statement in
the constructor.

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}
Super keyword

✓ The keyword super refers to the superclass of the class in which super appears.
✓ This keyword can be used in two ways:
(1) To call a superclass constructor
(2) To call a superclass method

1. Calling super class constructor

super() → invokes no argument constructor of its super class


super(parameters) → invokes super class constructor that matches the parameters

statement that uses the keyword super appear first in the constructor
Super keyword

1. Calling super class constructor class Super{


int i;
public Super(int x){
i=x;
}
public void show(){
System.out.println("i = "+i);
}
}
Parameterized constructors are class Sub extends Super{
not chained. To invoke super public Sub(int x){
super(x);
class’s parameterized constructor }
}
super is used public class DemoSuper{
public static void main(String[] a){
Sub t2 = new Sub(20);
t2.show();
}
}
Super keyword

2. Calling super class method class Super{


int i = 10;
public void show(){
System.out.println("i = "+i);
}
}
class Sub extends Super{
int i = 20;
public void show(){
To invoke super class’s hidden method super.show();
}
}
public class DemoSuper{
public static void main(String[] a){
Sub t2 = new Sub();
t2.show();
}
}
Super keyword

class Person{ void display()


int eid; {
String name; System.out.println(id+" "+name+" "+salary);
Person(int id, String n){ }
eid=id; }
name=n; class TestSuper{
} public static void main(String[] args){
} Emp e1=new Emp(1,"ankit",45000f);
class Emp extends Person{ e1.display();
float salary; }}
Emp(int id,String n,float sal){
super(id,n);//reusing parent constructor
salary=sal;
}
Super keyword

// Using super to overcome name hiding. void show() {


class A { System.out.println("i in superclass: "
int i; + super.i);
} System.out.println("i in subclass: " +
i);
// Create a subclass by extending class A. }
class B extends A { }
int i; // this i hides the i in A class UseSuper {
B(int a, int b) { public static void main(String args[]) {
super.i = a; // i in A B subOb = new B(1, 2);
i = b; // i in B subOb.show();
} }
}
Order of Constructor Calling in Multilevel Inheritance
class C extends B
class A
{
{
C()
A()
{
{
super();
System.out.println("Constructor of Class A has been
System.out.println("Constructor of Class C has been called");
called");
}
}
}
}
class Constructor_Call
class B extends A
{
{
public static void main(String[] args)
B()
{
{
System.out.println("------Welcome to Constructor call Demo-
super();
-----");
System.out.println("Constructor of Class B has been called");
C objc = new C();
}
}
}
}
Variables and Method Overriding

✓ Data Member Over riding class SubClass extends SuperClass{


int k=20;
void showk() {
class SuperClass {
System.out.println(" k " + k);
int i=10;
}
void showi() {
int i=30;
System.out.println("i " + i);
void showi() {
}
System.out.println("i " + i);
}
}
}

SuperClass SubClass
Class Members
Class Members
i,k, showi() and showk()
i and showi() Inherited Members

i and showi()
Variables and Method Overriding

public class DemoClass {


public static void main(String[] args){
SubClass sc = new SubClass();
sc.showi();
sc.showk();
}
}
Method Overriding

• A subclass extending the parent class has access to all the non-private data members and methods its parent
class.
• Most of the time the purpose of inheriting properties from the parent class and adding new methods is to
extend the behaviour of the parent class.
• However, sometimes, it is required to modify the behaviour of parent class. To modify the behaviour of the
parent class overriding is used.

Some important points that must be taken care while overriding a method:
i. An overriding method (largely) replaces the method it overrides.
ii. Each method in a parent class can be overridden at most once in any one of the subclass.
iii. Overriding methods must have exactly the same argument lists, both in type and in order.
iv. An overriding method must have exactly the same return type as the method it overrides.
v. Overriding is associated with inheritance.
Method Overriding
class Figure class Rectangle extends Figure
{ {
double sidea; Rectangle( double a , double b)
double sideb; {
Figure(double a, double b) super ( a, b);
{ }
sidea = a; double area ( )
sideb = b; {
} System.out.println("The Area of Rectangle:");
Figure(double a) return sidea*sideb;
{ }
sidea = a; }
sideb = a; class Squre extends Figure
} {
double area( ) Squre( double a )
{ {
System.out.println("Area inside figure is Undefined.");
return 0;
}
}
Method Overriding
Squre s = new Squre( 23.1);
super (a);
System.out.println("***** Welcome to
} Override Demo ******");
double area( ) f.area();
{ System.out.println(" "+r.area());
System.out.println("Area of Squre: "); System.out.println(" "+s.area());
return sidea*sidea; }
} }
} Output:
class Area_Overrid ***** Welcome to Override Demo ******
{ Area inside figure is Undefined.
public static void main(String[] args) The Area of Rectangle:
{ 1925.46
Figure f = new Figure(20.9, 67.9); Area of Squre:
Rectangle r = new Rectangle( 34.2, 56.3); 533.61
Object Class and its Methods

Every class in Java is descended from the java.lang.Object class

public class Circle { public class Circle extends Object {


... Equivalent
...
} }

1. public String toString():


✓ toString() method returns a string representation of the object
✓ returns a string consisting of a class name of which the object is an instance, the at sign
(@), and a number representing this object

Circle c = new Circle();


System.out.println(c.toString()); will display something like Circle@15037e5

✓ override the toString() method to get desired description of object.


Object Class and its Methods

2. public Boolean equals(Object o)

✓ tests whether two objects are equal

✓ Default implementation checks whether two reference variables point to the same
object
public Boolean equals(Object o){
return( this == o)
}
✓ Method can be over ridden
Access Modifiers

✓ Specify how class and class members are accesses

✓ Also known as visibility modifiers


Visibility increases
✓ private, default, protected, public private, default, protected, public

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -
Access Modifiers
Package 1 Package 2
Class 1
public a
Private b All are declared
Class 4
default c here and are
Protected d accessible here
Only a is accessible here through
Class 2
object of Class 1

Only a,c and d are accessible here Class 5 extends class 1 of package 1
through object of Class 1

Class 3 extends class 1 Only a and d are accessible here

Only a,c and d are accessible here


Scope of a variable

✓ Specify the visibility of a variable

Local variables: Scope is restricted to block, in which variable is defined, only

Instance and static data members : visibility as per visibility modifiers

You might also like