inheritance, Packages and Interfaces.pptx

vanithasounder 13 views 48 slides Oct 14, 2024
Slide 1
Slide 1 of 48
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48

About This Presentation

Java Inheritance


Slide Content

CS3391 – Object oriented programming UNIT II INHERITANCE, PACKAGES AND INTERFACES 09/18/2024 1

Inheritance 09/18/2024 2

REVISION More than one method have Same name but has defined with different parameter list of the class. Object can be passed as parameters for the method invocation as well return back. An inner class is a class that is defined inside another class. A class as static if and only if it is a nested class. Declare an inner class with the static modifier are static nested class. Overloading methods Objects as parameter, returning object Static, nested and inner class 09/18/2024 3

Topics Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –Abstract Classes – Final with Inheritance - Interfaces 09/18/2024 4

Introduction Code Reusability, overriding, extending and reducing redundancy Inherits properties and behaviors of parents/ancestors. Why? Technical Terms Inheritance 09/18/2024 5

Definition Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object . Create new classes that are built upon existing classes . Hence it can reuse methods and fields of parent class as well add its own methods and fields. What? 09/18/2024 6

Definition Sub Class A class inherits from another class. Inherits all the properties and behaviors Add new methods and fields A new class is inherited called as sub class, derived class, child class . Super Class A class derives another class. Grant their properties and behaviors for further code reusability. Existing class are super class, parent class and base class. 09/18/2024 7

Terminologies Keyword: extends Syntax class DerivedClass extends BaseClass { //methods and fields } Relationship IS-A relationship Example, Orange is a Fruit Class Subclass Superclass Reusability 09/18/2024 8

Key Features Reusability: The code written in the Superclass is common to all subclasses. Child classes can directly use the parent class code . Method Overriding:   Method Overriding  is achievable only through Inheritance. It is one of the ways by which Java achieves Run Time Polymorphism. Abstraction:  The concept of abstract where we do not have to provide all details, is achieved through inheritance.  Abstraction  only shows the functionality to the user. Code Reusability Method overriding abstraction 09/18/2024 9

Examples class Employee { float salary=40000; } class Programmer extends Employee { int bonus=10000; public static void main(String args []){ Programmer p=new Programmer(); System.out.println ("Programmer salary is:"+ p.salary ); System.out.println ("Bonus of Programmer is:"+ p.bonus ); } } Programmer is a Employee 09/18/2024 10

Exercise Create a base class, college that consists college code and name, address. It derives child class department that consists department code and name. Then display college details along with department details. 09/18/2024 11

Java Inheritance Types Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance Hybrid Inheritance In single-Inheritance , a sub-class is derived from only one super class class One { public void One_display () { System.out.println (“ Paavai Engineering College”); } } class Two extends One { public void Two_display () { System.out.println (“Department of CSE( IoT )”); } } public Class Main{ public Static void main(String args []){ Two t=new Two(); t.One_display (); t.Two_display (); }} 09/18/2024 12

Java Inheritance Types Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance Hybrid Inheritance In Multilevel Inheritance , a derived class of a base class can derive a sub class. (Chain of Inheritance). class One { public void One_display () { System.out.println (“ Paavai Engineering College”); } } class Two extends One { public void Two_display () { System.out.println (“Department of CSE( IoT )”); } } class Three extends Two { public void Three_display () { System.out.println (“2023 – 2027 Batch”); } } Public Class Main{ public Static void main(String args []){ Three t=new Three(); t.One_display (); t.Two_display (); t.Three_display (); }} 09/18/2024 13

Java Inheritance Types Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance Hybrid Inheritance In Hierarchical Inheritance , a super class derives more than one class. class One { public void One_display () { System.out.println (“ Paavai Engineering College”); } } class Two extends One { public void Two_display () { System.out.println (“Department of CSE( IoT )”); } } class Three extends One { public void Three_display () { System.out.println (“Department of AI-ML”); } } Public Class Main{ public Static void main(String args []){ Two t=new Two(); t.One_display (); t.Two_display (); Three r=new Three(); r.One_display (); r.Three_display (); }} 09/18/2024 14

Java Inheritance Types Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance Hybrid Inheritance In Multiple Inheritance , A child class have more than one super class. It is achieved via Interface. Keyword: implements . 09/18/2024 15 To access the interface methods, the interface must be "implemented"

Java Inheritance Types Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance Hybrid Inheritance In Hybrid Inheritance , composition of two or more types of inheritance. class C { public void disp () { System.out.println ("C"); } } class A extends C { public void disp () { System.out.println ("A"); } } class B extends C { public void disp () { System.out.println ("B"); } } public class D extends A { public void disp () { System.out.println ("D"); } public static void main(String args []) { D obj = new D(); obj.disp (); } } Hierarchical and Single Inheritance 09/18/2024 16 Class C Class A Class B Class D Single and Multiple Inheritance (not supported but can be achieved through interface) Multilevel and Hierarchical Inheritance Hierarchical and Single Inheritance Multiple and Multilevel Inheritance

Interfaces Java does not support multiple inheritance . To support multiple inheritance concept only through Interfaces . To access the interface methods , the interface must be " implemented“ by another class with the  implements keyword (instead of extends ). An interface is a completely "abstract class" that is used to group related methods with empty bodies 09/18/2024 17

Syntax 09/18/2024 18 interface < interface_name >{              // declare constant fields       // declare methods that abstract        // by default.   }  Why And When To Use Interfaces? 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can  implement  multiple interfaces.

Reason… 09/18/2024 19

Points to be followed .. 09/18/2024 20 Interfaces can have abstract methods and variables . It cannot have a method body. It cannot be instantiated just like the abstract class. Interface fields are public, static and final by default, and the methods are public and abstract . Ie , The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.

Possible Java Interfaces Example 09/18/2024 21 interface printable{   void  print();   }   class  A6  implements  printable{   public   void  print(){ System.out.println ("Hello");}      public   static   void  main(String  args []){   A6  obj  =  new  A6();   obj.print ();    }   }   the Printable interface has only one method, and its implementation is provided in the A6 class .

An interface Examcell is implemented at IoT class 09/18/2024 22 interface Examcell { public void internal(); // interface method (does not have a body ) public void CIA1(); // interface method (does not have a body) } // IoT "implements" the ExamCell interface class IoT implements ExamCell { public void internal() { // The body of internal() is provided here System.out.println (“This is Internal Test Assessment"); } public void CIA1() { // The body of CIA1 is provided here System.out.println (“CIA 1"); } } class Main { public static void main(String[] args ) { IoT s = new IoT (); // Create a Pig object s.internal (); s.CIA1(); } }

How to achieve abstraction? In a real scenario, an interface is defined by someone else , but its implementation is provided by different implementation providers . Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface . 09/18/2024 23

Scenario 2 09/18/2024 24 the Bank interface has only one method. Its implementation is provided by SBI and IOB classes. interface Bank{   float   rateOfInterest ();   }   class  SBI  implements  Bank{   public   float   rateOfInterest (){ return  9.15f;}   }   class  PNB  implements  Bank{   public   float   rateOfInterest (){ return  9.7f;}   }   class   Main{    public   static   void  main(String[]  args ){   Bank b= new  SBI();   System.out.println ("ROI: "+ b.rateOfInterest ());   }}  

Multiple Inheritance If a class implements multiple interfaces , or an interface extends multiple interfaces , it is known as multiple inheritance. 09/18/2024 25

Example, interface Printable{ void print(); } interface Showable{ void show(); } class A7 implements Printable,Showable { public void print(){ System.out.println ("Hello");} public void show(){ System.out.println ("Welcome");} public static void main(String args []){ A7 obj = new A7(); obj.print (); obj.show (); } } 09/18/2024 26

Interface Inheritance interface Printable{   void  print();   }    interface  Showable  extends  Printable{   void  show();   }    class  TestInterface4  implements  Showable{   public   void  print(){ System.out.println ("Hello");}   public   void  show(){ System.out.println ("Welcome");}      public   static   void  main(String  args []){   TestInterface4  obj  =  new  TestInterface4();   obj.print ();   obj.show ();   }   }   A class implements an interface, but one interface extends another interface. 09/18/2024 27

Super Keyword The  super keyword in Java is used in subclasses to access superclass members (attributes, constructors and methods ). Ie ., refer to its immediate superclass Two general forms. The first calls the superclass’ constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. 09/18/2024 28

Uses To call methods of the superclass that is overridden in the subclass. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name. To explicitly call superclass no- arg (default) or parameterized constructor from the subclass constructor. 09/18/2024 29

Accessing Parent Class Fields class Animal { String name = "Animal"; } class Dog extends Animal { String name = "Dog"; void printNames () { System.out.println ("Name in Dog class: " + name); System.out.println ("Name in Animal class: " + super.name ); } } public class Test { public static void main(String[] args ) { Dog dog = new Dog(); dog.printNames (); } } To access a field from the parent class when it is hidden by a field with the same name in the child class. 09/18/2024 30

Parent Methods access class Animal { void makeSound () { System.out.println ("Animal makes a sound."); } } class Dog extends Animal { void makeSound () { super.makeSound (); System.out.println ("Dog barks."); } } public class Test { public static void main(String[] args ) { Dog dog = new Dog(); dog.makeSound (); } } 09/18/2024 31

Accessing Parent Class Constructor To explicitly call a constructor of the parent class from the child class constructor. 09/18/2024 32 class Person{ int id; String name; Person( int id,String name){ this.id=id; this.name=name; } } class Emp extends Person{ float salary; Emp ( int id,String name,float salary){ super( id,name ); //reusing parent constructor this.salary =salary; } void display(){ System.out.println (id+" "+name+" "+salary);} } class TestSuper5{ public static void main(String[] args ){ Emp e1=new Emp (1,"ankit",45000f); e1.display(); }}

Calling Parent Class Methods from Overridden Methods class Base { void display() { System.out.println ("Display method in Base"); } } class Derived extends Base { void display() { super.display (); // Calls the display method of Base class System.out.println ("Display method in Derived"); } } public class Test { public static void main(String[] args ) { Derived obj = new Derived(); obj.display (); } } To invoke the original implementation of a method in the parent class when it is overridden in the child class. 09/18/2024 33

Method Overriding If subclass (child class) has the same method as declared in the parent class , it is known as  method overriding in Java . It provides the specific implementation of a method which is already provided by its superclass. Achieves runtime polymorphism Rules for Java Method Overriding 09/18/2024 34 The method must have the same name as in the parent class The method must have the same parameter as in the parent class . Final and static methods, if methods are not inherited, and constructor cannot be overridden. There must be an IS-A relationship (inheritance).

Example Class A { int a1; A( int i){ a1=i; } } void show(){ System.out.println (“Class A a1=“+a1”);} } Class B extends A { int b1; B( int j,int k){ super(j); b1=k; } } void show(){ super.show (); system.out.println (“Class B b1=“+b1);} } 09/18/2024 35

Dynamic method Dispatch Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time , rather than compile time. overridden method is called through a superclass reference A superclass reference variable can refer to a subclass object. This is also known as upcasting 09/18/2024 36

09/18/2024 37

Advantages Dynamic method dispatch allow Java to support  overriding of methods  which is central for run-time polymorphism. It allows a class to specify methods that will be common to all of its derivatives , while allowing subclasses to define the specific implementation of some or all of those methods . It also allow subclasses to add its specific methods subclasses to define the specific implementation of some. 09/18/2024 38

Abstract class and methods Data  abstraction  is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either   abstract classes  or  interfaces. The abstract keyword is a non-access modifier, used for classes and methods: Abstract class:  is a restricted class that cannot be used to create objects ( to access it, it must be inherited from another class ). Abstract method:  can only be used in an abstract class, and it does not have a body . The body is provided by the subclass (inherited from ). An abstract class can have both abstract and regular methods 09/18/2024 39

Example abstract class Animal { public abstract void animalSound (); public void sleep() { System.out.println (" Zzz "); } } How? 09/18/2024 40 it is not possible to create an object of the Animal class. To access the abstract class, it must be inherited from another class.  To achieve security - hide certain details and only show the important details of an object. Why And When To Use Abstract Classes and Methods?

09/18/2024 41 abstract class Animal { public abstract void animalSound (); public void sleep() { System.out.println (" Zzz "); } } class Pig extends Animal { public void animalSound () { System.out.println ("The pig says: wee wee "); } } class Main { public static void main(String[] args ) { Pig myPig = new Pig(); myPig.animalSound (); myPig.sleep (); } } // Abstract class // Abstract method (does not have a body) // Regular method // Subclass (inherit from Animal) // The body of animalSound () is provided here // Create a Pig object

Final Set a variable to final, to prevent it from being overridden/modified. 09/18/2024 42 public class Main { final int x = 10; public static void main(String[] args ) { Main myObj = new Main(); myObj.x = 25; System.out.println ( myObj.x ); } } // will generate an error: cannot assign a value to a final variable The  final keyword  in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class

09/18/2024 43 If you make any method as final, you cannot override it. class Bike{      final   void  run(){ System.out.println ("running");}   }         class  Honda  extends  Bike{       void  run(){ System.out.println ("running safely with 100kmph");}             public   static   void  main(String  args []){      Honda  honda =  new  Honda();       honda.run ();      }   }   Output : Compile Time Error

If you make any class as final, you cannot extend it. 09/18/2024 44 final class Bike{} class Honda1 extends Bike{ void run(){ System.out.println ("running safely with 100kmph");} public static void main(String args []){ Honda1 honda = new Honda1(); honda.run (); } } Output : Compile Time Error

Packages A package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces Think of it as  a folder in a file directory . We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: Built-in Packages (packages from the Java API) User-defined Packages (create your own packages ) 09/18/2024 45 import package . name . Class ; // Import a single class import package . name . * ; // Import the whole package import java . util . Scanner ;

09/18/2024 46 import java.util.Scanner ; class MyClass { public static void main(String[] args ) { Scanner myObj = new Scanner(System.in); System.out.println ("Enter username"); String userName = myObj.nextLine (); System.out.println ("Username is: " + userName ); } }

User-defined Packages To create a package, use the package keyword 09/18/2024 47 package mypack ; public class ClassOne { public void methodClassOne () { System.out.println ("Hello there its ClassOne "); } } └── root └── mypack └── ClassOne.java import mypack.ClassOne ; public class Testing { public static void main(String[] args ) { ClassOne b = new ClassOne (); b.methodClassOne (); } }

THANK YOU 09/18/2024 48