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

Lesson 5

Lesson 5 covers key concepts of Java inheritance, including access levels, the use of the super keyword, and the principles of polymorphism and method overriding. It also discusses the differences between abstract classes and interfaces, the reflection library, and the importance of the Object class methods. Additionally, it highlights the implications of multiple inheritance and the use of functional and marker interfaces.

Uploaded by

Uyen Hoang
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 views6 pages

Lesson 5

Lesson 5 covers key concepts of Java inheritance, including access levels, the use of the super keyword, and the principles of polymorphism and method overriding. It also discusses the differences between abstract classes and interfaces, the reflection library, and the importance of the Object class methods. Additionally, it highlights the implications of multiple inheritance and the use of functional and marker interfaces.

Uploaded by

Uyen Hoang
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/ 6

Lesson-5 – Class Notes

Default and Protected have package level access – both are same if your class has no Inheritance
If you have Inheritance relationship, even Protected can access other package too

Inheritance - IS - A relationship / Generalization.

Super class / Parent class - Top class - More General (Common)

Child class / Derived class (More specific, It can access everything from the parent except
private fields and methods

1. How to create Sub class


2. Use of super keyword
3. Declare object using Super type and assigning sub type to super type
4. Need of overriding
5. Polymorphism - Dynamic binding
6. Calling set Bonus from Employee object error
7. instance of
8. Rules about Constructor in Inheritance

If you have no constructors in both Parent and Child – Default constructor is automatic – No
Compilation Error
My Parent class have Default Constructor and my child class has no constructor – fine,
No compilation error – Automatic
If you have no default constructor in your parent, you have emplicit constructor in your
parent, must make use of any one parent constructor in your child class.

Employee Manager Example


Right Usage - Inheritance

1. You should have proper IS-A relationship, Example Manager is a Employee


2. Your inheritance must support Liskov Substitution principle(LSP),
If I need a type of Manager instance I can able substitute Employee instance

main(){
employee arraylist collections, Linked list manager collections
print(employee)
print(manager);

// API

}
public void print(List[] ea){
// Do something
}

Java Does not support Multiple inheritance

Legal - Class B extends A


illegal - Class C extends A,B --> ( Does not support multiple inheritance )
TO overcome the Multiple inheritance issue java supports to use multiple interface.
Java Does not support Multiple inheritance

Legal - Class B extends A


illegal - Class C extends A,B --> ( Does not support multiple inheritance )
TO overcome the Multiple inheritance issue java supports to use multiple interface.

About Number Type – Arithmetic operations

The Number class in Java is an abstract superclass for numeric wrapper classes
like Integer, Double, Float, Long, Short, and Byte. It provides methods to convert its instances
into different primitive types. However, it does not directly support arithmetic operations
because it serves as a generalized abstraction.

Number x = 20;
Number y = 20;
//Number z = x + y; // Cause compilation error

Right Usage

Number x = 20;
Number y = 20;
Double z1 = x.doubleValue() + y.doubleValue();
Number z2 = x.doubleValue() + y.doubleValue();
int sum = x.intValue() + y.intValue();

The Number class primarily provides methods for type conversion and polymorphic behavior.
While you cannot directly perform arithmetic or other operations on Number, you can use type-
specific methods (like intValue(), doubleValue()) to work with the underlying value.
Key differences between method overloading and method overriding in Java:

Aspect Overloading Overriding


Defining multiple methods with
Redefining a method in a subclass
the same name but different
Definition that already exists in the parent class
parameter lists (type, number, or
with the same signature.
order).
Happens between a parent class and
Relationship Happens within the same class.
a subclass.
The method signature (name,
Requires a difference in the
Parameters parameters, return type) must
number or type of parameters.
remain the same.
Can have different return types if
Return Type The return type must be the same
parameters differ.
The access level can be higher
No restrictions on access
Access Modifier visibility than the parent method or
modifiers.
same level of access modifier.
Binding
Resolved at compile time (static Resolved at runtime (dynamic
(Runtime/Compile-
binding). binding).
time)
Typically marked
Annotations Does not require annotations. with @Override to ensure
correctness.
Used to increase the readability of
Used to provide specific behavior in
the code by allowing the same
Use Case a subclass while keeping the method
method name for different
signature consistent.
operations.

Lesson 5 – Day – 2

To achieve Polymorphism to perform OO approach, you need a common type / Generalization


• Regular Inheritance / Abstract class
• Interfaces

Circle, Square, Triangle – All three has no relationship and no common type(Then we can use
Object type)

Create an array of all those three collection

Object arr[] = new Object{new Circle(34.5),


new Triangle(5.6.7.8),
new Square(5)};
for(Object ob : arr)
{
Ob.ComputerArea(); // You cannot access
If(ob instance of Circle)
Circle c = (Circle) ob;
}
Demo Purpose – Abstract class – Book – Subclass EBook and PaperBook

Interface

Pre-Java-8 Interface
è Pre-Java-8 – All methods are unimplemented, by default abstract methods
è By default all the fields are public static final
è By default all the methods public abstract à Unimplemented
è You cannot create object for an interface
è You cannot create constructor inside an interface
è You sub class can implements Interface
è One class can implement multiple interface
è One interface can inherit from other interface using extends keyword. May inherit one or
multiple interface

Drawbacks from Pre-Java-8

If you add some methods in the interface it affects your implementation. TO overcome this
drawback Java 8 introduces two implemented methods
1. Default
2. Static
You can able to override the Default implementation inside the class or you can go with
interface default implementation.

JDK 9

You can include private methods inside interface

Here’s a tabulated comparison between Java Abstract Class and Interface:

Feature Abstract Class Interface


A class that can have both abstract
A collection of abstract methods (prior
methods (without implementation)
Definition to Java 8). Starting with Java 8, it can
and concrete methods (with
have default and static methods.
implementation).
Does not support multiple inheritance
Multiple Supports multiple inheritance (a class
(a class can extend only one abstract
Inheritance can implement multiple interfaces).
class).
Feature Abstract Class Interface
Can have abstract methods, default
Can have abstract, concrete, static,
Method Types methods, static methods, and private
and final methods.
methods (since Java 9).
Can have instance variables (state) Can only have public static final
Fields
and static fields. variables (constants).
Methods and fields can have any Methods are public by default.
Access
access modifier (public, protected, Variables are public static final by
Modifiers
private). default.
Constructors Can have constructors. Cannot have constructors.
Used for creating a base class with Used for defining a contract that
Purpose
shared behavior that can be inherited. implementing classes must adhere to.
Keyword to
Use extends keyword to inherit. Use implements keyword to implement.
use
Use when you need a shared base Use when you need to define a contract
When to Use class with some common for classes without sharing
implementation. implementation.

Reflection Library

Retrieving a Class type is a fundamental part of Java Reflection. It allows you to examine or
modify the runtime behavior of applications. For example, you can dynamically create
objects, access fields, invoke methods, and much more.

Class.forName() is useful for dynamic class loading, where the class name is not known until
runtime. This is particularly useful in frameworks and libraries that need to load user-defined
classes or configurations.

Functional Interface – An interface has only one unimplemented method. This can be
implemented Lambdas. Example: Comparable

Marker Interface – Interface has no methods is called Mark interface. ( No methods which
useful to do cloning, data persistency). Example - API: Serializable

API example – Comparable Interface – Functional Interface

@FunctionalInterface
Interface test{
void display();
}

Not a functional interface


Interface test{
void display();
int add(int x, int y);
}

Object class

You have to get the benefit of Object methods only by overriding.


1. toString() à Print the status of the object
2. equals() à To compare two objects are equal
3. hashCode() à Will discuss in Lesson-11
4. clone() à Not covered

When you have an Inheritance for equals()

Case 1: You should have only one equals() from the parent, the comparison depends on
parent attributes, you can use instanceof statategy. PersonwithJob is a Person.

Case 2: Same class Strategy, you should have two equals - one parent and the child. You can
compare Person with Person type and PersonwithJob with PersonwithJob.

Drawback – Create asymmetric equality. ( I can’t compare Person and PersonwithJob) it


breaks the rule of IS-A Rule. Personwith Job is a not Person.
In both cases you have to make the sub class as final, to avoid confusion in the multi level
inheritance

Case 3: Composition (Has-A Relationship)

Cloning Types – Refer the Appexdix PPT for more information

1. Shallow clone
2. Deep clone.

Inside your class there is no composition – No worries you will get a copy.
When have a composition need to do deep copy.

You might also like