[go: up one dir, main page]

0% found this document useful (0 votes)
2 views35 pages

PSOOP_Lecture 06-2024-25

This document covers inheritance in Java, focusing on the use of the 'this' keyword, the 'super' keyword, and various concepts such as method overriding, polymorphism, and access modifiers. It explains how 'this' can refer to the current object, invoke methods, and manage constructor chaining, while 'super' is used to access hidden members in a subclass. Additionally, it discusses static and dynamic binding, the Object class, and the rules for method overriding, providing examples for clarity.

Uploaded by

nikahatkazi
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)
2 views35 pages

PSOOP_Lecture 06-2024-25

This document covers inheritance in Java, focusing on the use of the 'this' keyword, the 'super' keyword, and various concepts such as method overriding, polymorphism, and access modifiers. It explains how 'this' can refer to the current object, invoke methods, and manage constructor chaining, while 'super' is used to access hidden members in a subclass. Additionally, it discusses static and dynamic binding, the Object class, and the rules for method overriding, providing examples for clarity.

Uploaded by

nikahatkazi
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
You are on page 1/ 35

INHERITANCE IN JAVA-Part B

-Compiled by Nikahat Mulla


Agenda

• this keyword uses


• super and hiding data
• Multilevel Inheritance
• Method overriding rules
• Polymorphism and Types

2
'this' Keyword uses

- The 'this' keyword in Java is a reference to the current object.


- It is used in different scenarios to avoid confusion between instance variables
and parameters.
- 'this' can be used in:
1. Referring to Instance Variables
2. Invoking Current Class Methods
3. Invoking Current Class Constructors (Constructor Chaining)
4. Returning Current Class Instance
5. Passing as an Argument in Method Calls
6. Passing as an Argument in Constructor Calls
'this' Referring to Instance Variables

class Example {
int num;

Example(int num) {
this.num = num; // Using 'this' to differentiate between instance and
//local variable
}

void display() {
System.out.println("Number: " + num);
}

public static void main(String[] args) {


Example obj = new Example(10);
obj.display(); // Output: Number: 10
}
}
'this' Invoking Current Class
Methods

class Example {
void show() {
System.out.println("Inside show method");
}

void display() {
this.show(); // Using 'this' to call another method
}

public static void main(String[] args) {


Example obj = new Example();
obj.display(); // Output: Inside show method
}
}
Constructor Chaining using 'this'

class Example {
Example() {
this(10); // Calling another constructor
System.out.println("Default constructor");
}

Example(int num) {
System.out.println("Parameterized constructor: " + num);
}

public static void main(String[] args) {


Example obj = new Example();
}
}
'this' Returning Current Class
Instance

class Example {
Example getInstance() {
return this; // Returning current class instance
}

void display() {
System.out.println("Method called using 'this'");
}

public static void main(String[] args) {


Example obj = new Example().getInstance();
obj.display(); // Output: Method called using 'this'
}
}
Passing 'this' as a Method Argument

class Example {
void display(Example obj) {
System.out.println("Method called with 'this' reference");
}

void callMethod() {
display(this); // Passing current instance
}

public static void main(String[] args) {


Example obj = new Example();
obj.callMethod(); // Output: Method called with 'this' reference
}
}
Passing 'this' as a Constructor
Argument

class Example {
Example(Test obj) {
System.out.println("Constructor called with 'this' reference");
}

void callConstructor() {
new Test(this); // Passing current instance
}

public static void main(String[] args) {


Example obj = new Example();
obj.callConstructor();
}
}
Summary of 'this' Keyword

- The 'this' keyword helps in referring to the current object.


- It is useful to avoid confusion between instance variables and local variables.
- 'this' can be used to call methods, invoke constructors (constructor chaining),
return the current instance and pass itself as an argument.
- Proper use of 'this' improves code clarity and readability.
Using super to access hidden
members
• Used when member names of the subclass
hide members by the same name in the super
class
• super.member
• member can be either a method or an instance variable
• Refer MemberHidingExample.java
this vs. super

Sr. this super


No.
1. this refers to the current object super refers to the parent class
2. It is used in methods and It is used to call the methods or refer to
constructors when the arguments the data members of the super class
of these methods have the same from within methods of the child class
name as the data members of the
class
3. this can also be used in It is used in inheritance to call the
constructors as a constructor call constructors of the parent classes from
to other constructors and can be constructors of the base class for
based as method parameter instantiating objects in the correct
order.
Single Inheritance-Revision
• Single class deriving from a base class
• All members of the base class except private
and default are accessible to any subclass
from everywhere.
• However, if the subclass is within the same
folder (package), all members of the base
class except private are accessible inside the
subclass.
Access Modifiers & Inheritance in Java

| Modifier | Same | Same | Different | Different |


| | Class | Package | Package | Package |
| | | |(Subclass)| (Non-Sub |
| | | | |class) |
|--------------|------------|--------------|-----------------------------|
| private | Yes | No | No | No |
| default | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Example: Access Modifiers in Java

class Parent {
private int privateVar = 10;
int defaultVar = 20;
protected int protectedVar = 30;
public int publicVar = 40;
}

class Child extends Parent {


void display() {
// System.out.println(privateVar); // Not accessible (private)
System.out.println(defaultVar); // Accessible (same package)
System.out.println(protectedVar); // Accessible (inherited)
System.out.println(publicVar); // Accessible (public)
}
}
Polymorphism
• Means one entity having many (poly) forms
(morph)

• We can have multiple methods with the same


name in the same class, i.e. Method
Overloading

• Capability of an action or method to do


different things based on the object that it is
acting upon, i.e. Method Overriding
Method Overloading
• Two methods in a class can have same name,
provided their signature is different

class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) { Same name with different
System.out.println("int i = " + i); parameters
}
static void myPrint(double d) {
System.out.println("double d = " + d);
}
}
Method Overriding
• Useful if a derived class needs to have a different
implementation of a certain method from that of the superclass

• A subclass can override a method defined in its superclass by


providing a new implementation for that method

• The new method definition must have the same method


signature (i.e., method name & parameters) and return type
Types of Polymorphism
• Polymorphism is exhibited using method overloading and
method overriding
• There are two types of polymorphism depending upon on the
time of binding a method to its implementation.
• Binding happens when a method invocation is bound to an
implementation
▪ Involves lookup of the method in the class, or one of its
parents
▪ Both method names & parameters are checked
• Can happen at:
▪ Compilation Time (Static Binding->Static/ Compile Time
Polymorphism/Early Binding)
▪ Execution Time (Dynamic Binding->Dynamic/ Run-time
Polymorphism/Late Binding)
Static Binding
• Static binding is done by the compiler
• When it can determine the type of an object

• Method calls are bound to their


implementation immediately
public class MotorBike
{
public void revEngine() {…}
}
MotorBike bike = new MotorBike();
bike.revEngine();
Dynamic Binding
• When an object’s class cannot be determined at compile time

• JVM (not the compiler) has to bind a method call to its implementation

• Instances of a sub-class can be treated as instances of the parent class

• So the compiler doesn’t know its type, just knows its base type

public class Mammal { .. . . . }


public class Dog extends Mammal { . . . . }
public class Cat extends Mammal { . . . . }
Mammal m;
m = new Dog( );
m.speak(); // Invokes Dog’s implementation
m= new Cat();
m.speak(); // Invokes Cat’s implementation
Using Parent class reference to call
child class methods
• We can assign a variable of a certain class type with an instance of that particular
class or an instance of any subclass of that class

public class Mammal { .. . . . }


public class Dog extends Mammal { . . . . }
public class Cat extends Mammal { . . . . }
Mammal m;//parent class reference
m = new Dog( );//m contains child class
object
m.speak(); // Invokes Dog’s implementation,
//dogs bark (speaking for a dog is barking-
//same name, different behavior)
m= new Cat();
m.speak(); // Invokes Cat’s implementation,
//cat meows (speaking for a cat is meowing-
//same name, different behavior)
Type Casting for Reference Types
• We can assign a variable of a certain class type with an instance of that
particular class or an instance of any subclass of that class

public class Mammal { .. . . . }


public class Dog extends Mammal { . . . . }

• When we cast a reference along the class hierarchy in a direction from


the root class towards the subclasses, it’s a downcast

Mammal m=new Dog();


Dog d=(Dog) m; // explicit casting

• When we cast a reference along the class hierarchy in a direction from


the sub classes towards the root, it’s an upcast

Mammal m=new Dog();// implicit casting


The Object Class
• Object is the base class for all Java classes Object
• Every class extends this class directly or
indirectly
• Present in the package java.lang which is
imported by default into all java
programs
• It provides fundamental methods that
can be overridden.
A
• Methods like equals(), hashCode(), and
toString() are commonly used

class A
{ B

}
public class B extends A
{

}
Common Methods of Object Class

- hashCode(): Returns a unique integer hash code for an object.


- toString(): Returns a string representation of the object.
- equals(Object obj): Checks if two objects are equal.
- clone(): Creates a duplicate of the object (requires Cloneable interface).
- getClass(): Returns the runtime class of an object.
- wait(), notify(), notifyAll(): Used for thread synchronization.
Example: Overriding toString()
Method
class Student {
String name;
int id;

Student(String name, int id) {


this.name = name;
this.id = id;
}

public String toString() {


return "Student{name='" + name + "', id=" + id + "}";
}

public static void main(String[] args) {


Student s1 = new Student("Alice", 101);
System.out.println(s1); // Calls toString()
}
}
Example: Overriding equals()
Method
class Student {
String name;
int id;
Student(String name, int id) {
this.name = name;
this.id = id;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass())
return false;
Student student = (Student) obj;
return id == student.id && name.equals(student.name);
}
public static void main(String[] args) {
Student s1 = new Student("Alice", 101);
Student s2 = new Student("Alice", 101);
System.out.println(s1.equals(s2)); // Output: true
}
}
Example: Overriding hashCode()
Method
class Student {
String name;
int id;

Student(String name, int id) {


this.name = name;
this.id = id;
}

@Override
public int hashCode() {
return id * 31 + name.hashCode();
}

public static void main(String[] args) {


Student s1 = new Student("Alice", 101);
System.out.println(s1.hashCode()); // Unique integer
//value
}
}
Conclusion

- The Object class is the parent class of all Java classes.


- Methods like toString(), equals(), and hashCode() are commonly
overridden.
- These methods help in object comparison, representation, and unique
identification.
- Understanding these methods is essential for writing efficient Java
applications.
Recap: Multilevel Inheritance
• Extend the Rectangle class to create a new class Box with feature
height. Add the method volume and override the toString()
method in all classes.
• Refer Box.java
final keyword (pre-reads)
• Using final to prevent Overriding
• When a method in the superclass is declared as final, it cannot be
overridden in the subclass

• Using final to prevent Inheritance


• When a class is declared as final, it cannot be inherited

• final can also be used to make a data member


of constant value. For e.g.
final int empid;
Employee(int id){empid=id;}
Rules for Method Overriding (pre-
reads)
1. Method must have same name, same arguments
2. It can broaden visibility in child class but not narrow it
down. For example, if a method is protected in the parent
class and overridden in the child class, then it can be made
protected or public but not private in the child class.
3. Return type of overridden method should be same or if it
returns an object its return type in child class can be the
child class type.
4. Constructors and private methods cannot be overridden
5. A subclass cannot call the parent class method using its
reference, if the method is overridden. Always the child class
variant will be called.
6. static and final methods cannot be overridden.
The instanceof Operator (pre-reads)
• Used to check the actual type of an object

• Has two operands:


• A reference to an object on the left
• A class name on the right

• Returns true or false based on whether the


object is an instance of the named class or
any of that class's subclasses
The instanceof Operator (Contd…)
(pre-reads)

• An Example: A class definition

public class MotorBike extends Vehicle


{

}

Vehicle bike = new MotorBike();


if (bike instanceOf MotorBike)
{
-------
}

Check whether the bike


reference is an instance
of MotorBike or not
Thank You

You might also like