0% found this document useful (0 votes)
3 views50 pages

Unit 3

The document provides an overview of inheritance in Java, detailing types such as single, multilevel, hierarchical, and multiple inheritance. It also explains key concepts like polymorphism, method overriding, and the use of the super keyword, along with access specifiers and the role of packages. Additionally, it covers abstract classes and interfaces, generics, and wildcards in generics.

Uploaded by

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

Unit 3

The document provides an overview of inheritance in Java, detailing types such as single, multilevel, hierarchical, and multiple inheritance. It also explains key concepts like polymorphism, method overriding, and the use of the super keyword, along with access specifiers and the role of packages. Additionally, it covers abstract classes and interfaces, generics, and wildcards in generics.

Uploaded by

varunchandran01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Unit 3

Archana NS
Department of Computer Applications
Don Bosco College
TC Palya
• Inheritance is a mechanism in Java by
which one class inherits the properties
(fields) and behaviors (methods) of
another class.
• Purpose: Promotes code reusability and
Introduction to establishes a natural hierarchy between
classes.
Inheritance in • Syntax
Java class SubClass extends SuperClass {
// additional fields and methods
}
• Single Inheritance
• A subclass inherits from one superclass
class Animal {
void eat() {
System.out.println("This animal eats
Types of food.");
}
Inheritance in }
Java class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Types of Inheritance

Multilevel
Inheritance:

A class is derived from


another class, which is
also derived from
another class.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Mammal extends Animal {


void breathe() {
System.out.println("This mammal breathes.");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("The dog barks.");
}
}
Types of inheritance

Hierarchical Inheritance

Multiple subclasses inherit from a single


superclass.
Multiple Inheritance (Through
Interfaces):
A class can implement multiple interfaces.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
This Photo by Unknown Author is licensed under CC BY-SA
• Super Class (Parent Class):
• The class whose properties
and methods are inherited
Super and by another class.
Subclass • Sub Class (Child Class)
• The class that inherits
properties and methods from
another class.
• Polymorphism is the ability of a
single interface to support
multiple underlying forms
(data types).
Polymorphism • Compile-time
Polymorphism (Method
Overloading)
• Run-time Polymorphism
(Method Overriding)
• Method overriding is redefining
a method in a subclass that
already exists in the superclass
with the same signature (name
Method and parameters).
Overriding • Allows a subclass to provide a
specific implementation of a
method that is already defined
in its superclass.Supports
runtime polymorphism.
Overloading
• Method overloading allows a class
to have more than one method
with the same name, provided
their parameter lists are different.
• Overloading increases the
readability of the program by
allowing the same method name to
handle different types of inputs.
• Parameters: Methods must have
different parameter lists (either
different types, different number of
parameters, or both).
• Return Type: Methods can have
different return types, although
return type alone is not enough to
distinguish overloaded methods.
• Access Modifier: Methods can have
different access modifiers
• Method overriding occurs when a
subclass provides a specific
implementation of a method that is
already defined in its superclass.
• Overriding allows a subclass to provide a
specific implementation for a method,
supporting runtime polymorphism.
• Methods must have the same parameter
Overriding lists (same type, number, and order).
• Methods must have the same return
type, or a subtype (covariant return
type).
• The overriding method cannot have a
more restrictive access modifier than the
overridden method.
• Overriding is an example of runtime
polymorphism (dynamic binding),
Rules
Must have the
same name and
parameters.

Should have the


same return type

The overridden
method must be
accessible in the
subclass.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks.");
}
}

public class TestOverriding {


public static void main(String[] args) {
Dog a = new Dog();
a.makeSound(); // Dog's makeSound() is called
}
}
Dynamic Binding

Dynamic binding (late binding) refers to the process


where the method call is resolved at runtime rather
than compile-time.
Allows Java to support polymorphism and method
overriding.
Ensures that the most specific method is invoked for
an object, even when referenced by a superclass
type.
Super Keyword
Refer super class object.

Uses

To call super class method from sub class.

If superclass and subclass contains the same variable then we can


access the superclass variable using super keyword.
To call superclass constructor from subclass constructor.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
eating…
}
barking…
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){ animal is created
super(); dog is created

System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Final Keyword

WITH WITH WITH


VARIABLES METHODS CLASSES
Final variable final method
• Final key word will make a variable constant
• E.g. final int b=20;
• Final method can not be overridden.
class finaldemo{
final void secure(){
System.out.println(“This is highly secure”);
class demo extends finaldemo{
void secure(){
System.out.println(“Hi”); #error
}
}
Final keyword is used before
class keyword to make a
class final.

Final Final classes can not be

classes
inherited.

Final in-built classes in java


are math class string class.
Abstract keyword

• Abstract method and class


• Abstract method: A method
without any implementation.
• Abstract class: A class that
contains one or more abstract
methods. No objects for abstract
classes.
Abstract class
• An abstract class must be
declared with an abstract
keyword.
• It can have abstract and non-
abstract methods.
• It cannot be instantiated.
• It can have final methods which
will force the subclass not to
change the body of the method.
• Child class should implement all
the abstract method of parent
class.
abstract class Bike{
abstract void run();

}
class Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Honda obj = new Honda();
obj.run();
}
}
Interface in Java

• An interface is a reference type in


Java, similar to a class, that can
contain only abstract methods, static
methods, and final variables.
• There can be only abstract methods in
the Java interface, not the method
body.
• Class: full implemented
• Interface: fully unimplemented.
• Abstract class: partially implemented.
Interfaces

• Contain any number of methods.


• .java extension.
• Does not contain any constructors.
• Implemented by a class.
• An interface can extend multiple
interfaces.
• variables in the interface are final,
public, and static.
Interface
• Syntax:
• interface interface name{
public static variables;
public abstract methods;
}

interface animal{
int age=10;
void eat();
void travel();
}
• Implementing interfaces

import java.io.*; public static void main(String[] args)


interface In1 { {
TestClass t = new TestClass();
final int a = 10;
t.display();
void display(); System.out.println(t.a);
} }
class TestClass implements In1 { }
public void display(){
System.out.println(“Hello");
}
Extending interfaces
• Like class extends another class
interface i1{
void method1()
}
interface i2 extends i1{
void method2();
}
An interface can extend more than one
interfaces.
Packages
• A java package is a group of similar
types of classes, interfaces and sub-
packages.
• Package in java can be categorized in
two form, built-in package and user-
defined package.
• lang, awt, javax, swing, net, io, util,
sql etc.
• Java package is used to categorize
the classes and interfaces so that
they can be easily maintained.
• Java package provides access
protection.
• Java package removes naming
collision.
User defined packages
package pkg;
package pkg1.pkg2.pkg3;
Access specifiers

• In Java, access specifiers (also known


as access modifiers) are keywords
used to set the visibility of classes,
methods, and variables.
• They define the scope of access for
different parts of your code.
• Four main access specifiers in Java:
Public

• Keyword: public
• Visibility: Any class from any package
can access.
• Usage: Applied to classes, methods,
and variables.
Access
specifiers Protected

• Keyword: protected
• Visibility: Accessible within the same
package and by subclasses (including
those in different packages).
• Usage: Applied to methods and
variables. Not applicable to top-level
classes.
Default (Package-Private)

• Keyword: None (default)


• Visibility: Accessible only within the
same package.
• Usage: Applied to classes, methods,
and variables.
Access
specifiers Private

• Keyword: private
• Visibility: Accessible only within the
same class.
• Usage: Applied to methods and
variables.
• Not applicable to top-level classes.
This Photo by Unknown Author is licensed under CC BY-SA
java.lang package.

Every class in java are directly or indirectly derived from


object class.
Topmost class in java.

Following declarations are valid.

Object Object obj;

class Obj=null;

Obj=new Object();

Student std=new Student();

Obj=std;
Object •class java.lang.Object
•getClass()
• Returns class name of the object.
•class Test
class • Object.getClass();
• Public class Test{

methods • Public static void


main(String args[])
• {
• Object obj1= new Object();
• System.out.println(obj1.get
Class());
• Test obj2=new Test();
• System.out.println(obj2.get
Class());
• }
Object •toString()
• Converts objects in to
•Java.lang.Object@7a8
1197d
class a string and returns it.
• Object obj1=new
methods Object();
• System.out.println(obj1
.toString());
hashCode()
• To get theh hash code of the object.
• Object obj=new Object();
• obj.hashCode();
Object class equals()
methods • For checking whether two objects are
equal or not.
• Student S1=new Student(1001);
• Student S2=new Student(1002);
• S1.equals(S2);
• Converting object of one class type to
object of another class type.
• Upcasting: Reference variable of
super class refers to object of
subclass. It can perform
implicitly/explicitly.
Casting • Eg: superclass obj= new subclass();
objects • Downcasting: When subclass
references refers to super class object
it is called narrowing or downcasting.
Can be done only explicitly.
• Eg: superclass obj1=new subclass();
• Subclass obj2=(subclass)obj1;
Instance of • Used to test whether an object is an
instance of the specified
type(class,subclass or interface).
operator • Objectname instanceOf calssname
class Animal { // Class definition }
class Dog extends Animal { // Class
definition }
public class demo {
public static void main(String[] args)
{
Animal myAnimal = new Animal();
Dog myDog = new Dog();
Animal myPet = new Dog();
Generic • Generics are a set of java language
features that allow the programmer
to use generic types and functions
Programmi and thus ensure type safety.

ng • Scenario: sorting of integers,


floats,double
Generic • A class that can be used with any
type of data.

class • Class name is followed by a type in


angular brackets.
Class classname <T>{
Class variables;
Class methods;
}
Classname<Integer> obj=new
classname<Integer>
Generic • A generic method is a method that can

methods
operate on objects of various types
• public class GenericMethodExample {
public static <T> void printArray(T[] inputArray) {
for (int i = 0; i < inputArray.length; i++) {
System.out.println(element);}}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
String[] stringArray = {"Hello", "World",
"Generic", "Methods"};
printArray(intArray); // Pass an Integer array
printArray(doubleArray); // Pass a Double array
System.out.println("\nArray of Strings:");
printArray(stringArray); // Pass a String array
}
}
Wildcards in Generics
• Wildcards in generics provide flexibility and reusability
when dealing with parameterized types.
• Unbounded Wildcard (?)
• Bounded Wildcard with an Upper Bound (? extends
Type)
• Bounded Wildcard with a Lower Bound (? super Type)
Wildcard Type Definition Use Case
Represents an unknown General methods that can
?
type accept any type
? extends Type Represents a type that is a Read-only operations where
subtype of Type the type is a specific class or
its subtype
? super Type Represents a type that is a Write operations where the
supertype of Type type is a specific class or its
supertype

You might also like