0% found this document useful (0 votes)
9 views49 pages

Inheritance

Inheritance in Java allows for the creation of new classes from existing ones, promoting code reusability and functionality extension. Java supports single inheritance and multiple levels of inheritance but does not allow multiple inheritance to prevent complexity. All classes in Java inherit from the java.lang.Object class, and constructors play a crucial role in the inheritance process, with specific rules governing their use and invocation.

Uploaded by

raoufdaiffi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views49 pages

Inheritance

Inheritance in Java allows for the creation of new classes from existing ones, promoting code reusability and functionality extension. Java supports single inheritance and multiple levels of inheritance but does not allow multiple inheritance to prevent complexity. All classes in Java inherit from the java.lang.Object class, and constructors play a crucial role in the inheritance process, with specific rules governing their use and invocation.

Uploaded by

raoufdaiffi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Inheritance

1
Introduction
• Inheritance is one of the key features of OOP that allows us to create
a new class from an existing class.
• The most important use of inheritance in Java is code reusability. The
code that is present in the parent class can be directly used by the
child class.
• The inheritance helps to extend the functionalities of a class. If you
have a base class with some functionalities, you can extend them by
using the inheritance in the derived class.

2
Introduction

• In Java, you can define a class to inherit from an existing class.


• Inheritance is the process by which the new child subclass automatically includes
any publicor protected fields and methods defined in the parent class.

3
3
Introduction
• We refer to any class that inherits from another class as a child class, or a
descendent of that class.

• We refer to the class that the child inherits from as the parent class, or an
ancestor of the class.
• If child X inherits from class Y, which in turn inherits from class Z, then X would be
considered an indirect child, or descendent, of class Z.

4
4
Introduction
• Java supports single inheritance, by which a class may inherit from only one
direct parent class.

• Java also supports multiple levels of inheritance, by which one class may extend
another class, which in turn extends another class.

• You can extend a class any number of times, allowing each descendent to gain access
to its ancestor’s members.

5
5
Introduction
• Multiple inheritance: a class may have multiple direct parents.
• Java doesn’t support multiple inheritance
• because studies have shown that multiple inheritance can lead to complex,
often difficult-to-maintain code.
• Java does allow one exception to the single inheritance rule: classes may
implement multiple interfaces (interfaces will be covered later on)

6
6
Introducing Class Inheritance
Animal
Animal Pet Friendly

Mammal Bird
Dog

Bat Tiger Parrot Eagle Husky Poodle

Single Inheritance Multiple Inheritance

7
7
Extending a Class

8
8
Extending a Class
We want to create two classes Animal.java Lion.java, where Lion
class extends the Animal class.

Assuming the two classes are in the same package, an import statement
is not required in Lion.java to access the Animal class.

9
9
Extending a Class
● Here are the contents of Animal.java:
public class Animal {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} 10
9
Extending a Class
And here are the contents of Lion.java:
public class Lion extends Animal {
private void roar() {
System.out.println("The "+getAge()+" year old lion Roars");
}
}
Notice the use of the extends keyword in Lion.java to indicate that the Lion class
extends from the Animal class.
In this example, we see that getAge() and setAge() are accessible by subclass
Lion, because they are marked as public in the parent class.
11
11
Extending a Class
The primitive age is marked as private and therefore not accessible from the
subclass Lion, as the following would not compile:
public class Lion extends Animal {
private void roar() {
System.out.println("The "+age+" year old lion Roars");
// DOES NOT COMPILE
}
}

12
12
Extending a Class
Despite the fact that age is inaccessible by the child class, if we have an
instance of a Lion object, there is still an age value that exists within the
instance.
The age value just cannot be directly referenced by the child class nor any
instance of the class.

In this manner, the Lion object is actually “bigger” than the Animal object
in the sense that it includes all the properties of the Animal object (although
not all of those properties may be directly accessible) along with its own set
of Lion attributes.

13
13
Preventing Inheritance
What if we don’t want my class to be extended by other classes?

What can we do?

14
14
Preventing Inheritance
• It is possible in Java to prevent a class from being extended by
marking the class with the finalmodifier.
• If you try to define a class that inherits from a final class, the compiler
will throw an error.

15
15
Java Object class
• In Java, all classes inherit from a single
class, java.lang.Object.
• Furthermore, java.lang.Object is the only
class that doesn’t have any parent classes.

16
16
Java Object class

17
Java Object class
The compiler automatically inserts code into any class that doesn’t
extend a specific class to make it child of Object class.
For example, consider the following two equivalent class definitions:

public class Zoo {


}

public class Zoo extends java.lang.Object {


}

22
18
Extending Object
If you define a new class that extends an existing class, Java doesn’t add
this syntax, although the new class still inherits from java.lang.Object.

– Since all classes inherit from java.lang.Object, extending an


existing class means the child automatically inherits from
java.lang.Object by construction.
This means that if you look at the inheritance structure of any class, it will
always end with java.lang.Object on the top of the tree

19
Inheritance and Constructors
• Every class has at least one constructor.
• In the case that no constructor is declared, the compiler will automatically
insert a default no-argument constructor.
• In the case of extending a class, though, things are a bit more interesting.

• In Java, the first statement of every constructor is either a call to another


constructor within the class, using this(), or a call to a constructor in the
direct parent class, using super().

• If a parent constructor takes arguments, the super constructor would also


take arguments.

20
public class Animal { private
int age;
public Animal(int age) {
super();
this.age = age;
}
}
public class Zebra extends Animal {
public Zebra(int age) {
super(age);
}
public Zebra() {
this(4);
} 26
} 21
Inheritance and Constructors
• In the first class, Animal, the first statement of the constructor is
a call to the parent constructor defined in java.lang.Object,
which takes no arguments.
• In the second class, Zebra, the first statement of the first constructor
is a call to Animal’s constructor, which takes a single argument.
• The class Zebra also includes a second no-argument constructor
that doesn’t call super() but instead calls the other constructor
within the Zebra class using this(4).

22
Defining Constructors
Like the this()command, the super() command may only be
used as the first statement of the constructor.
– For example, the following three class definitions will not compile

23
public class Zoo { public Zoo() {
System.out.println("Zoo created");
super(); // DOES NOT COMPILE
}}
public class Zoo {
public Zoo() {
super();
System.out.println("Zoo created");
super(); // DOES NOT COMPILE
}}
public class Zoo {
public Zoo() {
super();
super(); // DOES NOT COMPILE
24
}}
Defining Constructors
• The first class will not compile because the call to the parent constructor must be the
first statement of the constructor, not the second statement.
• In the second code snippet, super() is the first statement of the constructor, but it also
used as the third statement. Since super() can only be used as the first statement of the
constructor, the code will likewise not compile.
• In the third code, the same as previously, super() must be called only in the first
statement.

25
Defining Constructors
If the parent class has more than one constructor, the child class may
use any valid parent constructor in its definition.

33
26
Defining Constructors
public class Gorilla extends Animal {
public Gorilla(int age) {
super(age,"Gorilla");
}
public Gorilla() {
super(5);
}
}

27
Defining Constructors
In this example, the first child constructor takes one argument, age, and
calls the parent constructor, which takes two arguments, age and name.
The second child constructor takes no arguments, and it calls the parent
constructor, which takes one argument, age.
In this example, notice that the child constructors are not required to call
matching parent constructors. Any valid parent constructor is acceptable as
long as the appropriate input parameters to the parent constructor are
provided.

28
Compiler Enhancements
Up to now, we defined numerous classes that did not explicitly call the
parent constructor via the super() keyword, so why did the code
compile?

The answer is that the Java compiler automatically inserts a call to the no-
argument constructor super() if the first statement is not a call to the
parent constructor.

For example, the following three class and constructor definitions


are equivalent, because the compiler will automatically convert
them all to the last example:

29
public class Donkey {
}

public class Donkey {


public Donkey() {
}
}

public class Donkey {


public Donkey() {
super();
}
}
Make sure you understand the differences between these three Donkey
class definitions and why Java will automatically convert them all to the last
definition. 30
What happens if the parent class doesn’t have a no-argument
constructor?

Recall that the no-argument constructor is not required and only


inserted if there is no constructor defined in the class.

In this case, the Java compiler will not help and you must create
at least one constructor in your child class that explicitly calls a
parent constructor via the super() command.

31
For example, the following code will not compile:
public class Mammal { public
Mammal(int age) {}
}
public class Elephant extends Mammal {
// DOES NOT COMPILE
}

In this example no constructor is defined within the Elephant class, so the compiler
tries to insert a default no-argument constructor with a super() call, as it did in the
Donkey example.
The compiler stops, though, when it realizes there is no parent constructor that
takes no arguments. In this example, we must explicitly define at least one
constructor, as in the following code: 32
39
We can fix this, though, by adding a call to a parent constructor that takes a fixed argument:
public class Mammal {
public Mammal(int age) {
}
}
public class Elephant extends Mammal {
public Elephant() {
super(10);
}
}

This code will compile because we have added a constructor with an explicit call to a
parent constructor.
43
33
Note that the class Elephant now has a no-argument constructor even
though its parent class Mammal doesn’t.
Subclasses may define no-argument constructors even if their parent classes
do not, provided the constructor of the child maps to a parent constructor via
an explicit call of the super() command.

34
Reviewing Constructor Rules
1. The first statement of every constructor is a call to another constructor within
the class using this(), or a call to a constructor in the direct parent class
using super().
2. The super() call may not be used after the first statement of the
constructor.
3. If no super() call is declared in a constructor, Java will insert a no-
argument super() as the first statement of the constructor.
4. If the parent doesn’t have a no-argument constructor and the child doesn’t
define any constructors, the compiler will throw an error and try to insert a
default no-argument constructor into the child class.
5. If the parent doesn’t have a no-argument constructor, the compiler requires
an explicit call to a parent constructor in each child constructor.
35
Output?
class K {
public K() { System.out.println("k"); }
public K(int a) { System.out.println("K int"); }
}
public class T extends K{
public T() {System.out.println("T"); }
public T(int i) { System.out.println("T int"); }
public static void main(String[] args) {
T t1 = new T();
T t2 = new T(1);
}
} 3
36
Output
● k
● T
● k
● T int

4
37
Calling Constructors
The parent constructor is always executed before the child
constructor.
class Primate {
public Primate() { System.out.println("Primate"); }
}
class Ape extends Primate {
public Ape() { System.out.println("Ape"); }
}
public class Chimpanzee extends Ape {
public static void main(String[] args) {
new Chimpanzee();
}
} 5
38
Calling Constructors

• The compiler first inserts the super() command as the first


statement of both the Primate and Ape constructors.
• Next, the compiler inserts a default no-argument constructor in the
Chimpanzee class with super() as the first statement of the
constructor. The code will execute with the parent constructors called
first and yields the following output:
Primate
Ape
39
Calling Inherited Class Members
• Sub classes may use any public or protected
member of the parent class, including methods,
primitives, or object references.
• If the parent class and child class are part of the same
package, the child class may also use any default
members defined in the parent class.
• A child class may never access a private member of
the parent class, at least not through any direct
reference.
40
class Fish {
protected int size;
private int age;
public Fish(int age) { this.age = age; }
public int getAge() { return age; }
}
public class Shark extends Fish {
private int numberOfFins = 8;
public Shark(int age) { super(age); this.size = 4; }
public void displaySharkDetails() {
System.out.print("Shark with age: "+getAge());
System.out.print(" and "+size+" meters long");
System.out.print(" with "+numberOfFins+" fins");
}
} 9
41
Accessing Inherited Class Members
In the child class, we use the public method getAge() and
protected member size to access values in the parent class.

You know that you can use the keyword this to access a
member of the class.

You may also use this to access members of the parent class
that are accessible from the child class, since a child class
inherits all of its parent members.
4
3

Accessing Inherited Class Members



Consider the following alternative definition to the
displaySharkDetails() method in the previous example:

public void displaySharkDetails() {


System.out.print("Shark with age: "+this.getAge());
System.out.print(" and "+this.size+" meters long");
System.out.print(" with "+this.numberOfFins+" fins");
}
4
4

Accessing Inherited Class Members



you can also explicitly reference a member of the parent class by using the
super keyword, as in the following alternative definition of
displaySharkDetails():
public void displaySharkDetails() {
System.out.print("Shark with age: "+super.getAge());
System.out.print(" and "+super.size+" meters long");
System.out.print(" with "+this.numberOfFins+" fins");
}
Accessing Inherited Class Members
In the previous example, we could use this or super to access a member of the
parent class, but is the same true for a member of the child class?
Consider this example:
public void displaySharkDetails() {
System.out.print("Shark with age: "+super.getAge());
System.out.print(" and "+super.size+" meters long");
System.out.print(" with "+super.numberOfFins+"
fins"); // DOES NOT COMPILE
}

45
Accessing Inherited Class Members
This code will not compile because numberOfFins is only a
member of the current class, not the parent class. In other words,
we see that this and super may both be used for methods or
variables defined in the parent class, but only this may be used for
members defined in the current class.

Note: As we’ll see in the next lectures, if the child class overrides a
member of the parent class, this and super could have very
different effects when applied to a class member.
46
super() vs. super
this() and this are unrelated in Java. Likewise,
super() and super are quite different.

– The first, super(), is a statement that explicitly calls a parent constructor


and may only be used in the first line of a constructor of a child class.
The second, super, is a keyword used to reference a member
defined in a parent class and may be used throughout the child
– class.

47
super() vs. super

• For example, consider the following code:


public Rabbit(int age) {
super();
super.setAge(10);
}
• The first statement of the constructor calls the parent’s constructor, whereas
the second statement calls a function defined in the parent class.

48
super() vs. super
• Contrast this with the following code, which doesn’t compile:
public Rabbit(int age) { ,
super;
super().setAge(10);
//DOES NOT COMPILE
}
• This code looks similar to the previous example, but neither line of the
constructor will compile since they are using the keywords incorrectly.
49

You might also like