702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx

SAJITHABANUS 41 views 46 slides Sep 09, 2024
Slide 1
Slide 1 of 46
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

About This Presentation

OOPS PPT


Slide Content

CS3391-OBJECT ORIENTED PROGRAMMING UNIT 2 INHERITANCE, PACKAGES & INTERFACES by S.Sakkaravarthi, AP/IT Ramco Institute of Technology, Rajapalayam

UNIT 2-TOPICS Overloading Methods Objects as Parameters Returning Objects Static, Nested and Inner Classes Inheritance: Basics-Types of Inheritance Super keyword

UNIT 2-TOPICS Method Overriding-Dynamic Method Dispatch Abstract Classes-final with Inheritance Packages and Interfaces: Packages Packages and Member Access Importing Packages Interfaces

Overloading Methods When a class has more than one method having the same name but with different parameter lists , this feature is called  method overloading in Java . There are two ways to overload the method in java: 1.By Changing number of arguments 2.By Changing the data type

  public class  Overloadingdemo {     public static void  main(String args[]) {   //Compile Time  Polymorhism System.out.println( Adder.add (10,5) ); System.out.println( Adder.add (10,5,6) ) ; }   }  class   Adder {   static  int  add (int a, int b)    { return a+b; } static int add (int a, int b, int c) { return a+b+c; }   } Output: 15 21 Method Overloading-By Changing no of arguments

Method Overloading-By Changing no of arguments   public class  Overloadingdemo {     public static void  main(String args[]) {   Adder ar = new Adder(); //Compile Time  Polymorhism System.out.println(ar .add (10,5) ); System.out.println(ar .add (10,5,6) ) ; }   }  class   Adder {    int  add (int a, int b)    { return a+b; } int add (int a, int b, int c) { return a+b+c; }   } Output: 15 21

  public class  Overloadingdemo {     public static void  main(String args[]) {   //Compile Time  Polymorhism System.out.println( Adder.add (10,5) ); System.out.println( Adder.add (1.1,5.5,6.2) ) ; }   }   class   Adder {   static  int  add (int a, int b)    { return a+b; } static float add (float a, float b, float c) { return a+b+c; }   } Output: 15 12.8 Method Overloading-By Changing data type of arguments

  public class  Overloadingdemo {     public static void  main(String args[]) {   Adder ar = new Adder(); //Compile Time  Polymorhism System.out.println(ar .add (10,5) ); System.out.println(ar .add (1.1,5.5,6.2) ) ; }   }   class   Adder {   int  add (int a, int b)    { return a+b; } float add (float a, float b, float c) { return a+b+c; }   } Output: 15 12.8 Method Overloading-By Changing data type of arguments

Benefits of Method Overloading Increases the readability of the program Provides flexibility to call the same method for different types of data. Reduces the execution time because the binding is done in compilation time itself. Use the code again, which saves memory

Objects as Parameters Like primitive types, Objects can be passed as parameters to methods in Java. When passing an object as a parameter to a method, a reference to the object is passed rather than a copy of the object itself. This means that any modifications made to the object within the method will have an impact on the original object.

Object as Parameter public class Student { private int rollno; private String name; public MyClass(int r, String n) { rollno = r; name = n; } public void display(Student obj) // Method with object as parameter { System.out.println(“Roll no is:"+ obj.rollno ); System.out.println(“ Name is:" + obj.name); }

Object as Parameter-Contd… public static void main(String[] args) { Student s1 = new Student(10, "Hello"); Student s2 = new Student(20, "World"); // Call the method with object as parameter s1 .display(s2); } }

Returning Objects A method can have the class name as its return type. Therefore it must return the object of the exact class or its subclass. Java methods can also return objects. A reference to the object is returned when an object is returned from a method, and the calling method can use that reference to access the object.

  public class  SumReturnDemo {     public static void  main(String args[]) {   SumReturn obj1=newSumReturn(50); SumReturn obj2; obj2=obj1.addition(); obj2.display(); }   }   class   SumReturn {   private int a; public SumReturn (int i) {  a=i; } public SumReturn addition ( ) { SumReturn result = new SumReturn(a + 100);  return result; } } public void display( ){ System.out.println(“Addition:”+a); } } Addition : 150 Java Program - Returning Objects

Method Overriding Method Overriding refers to the ability of a subclass to provide a specific implementation of a method that is already defined in its super class. It allows a subclass to modify the behavior of an inherited method from its superclass. Rules for Method Overriding: 1.Method must have same name as in the parent class 2.Method must have same parameter as in the parent class 3.There must be IS-A relationship (inheritance)

class Test{ public static void main(String args []) { SBI sbi =new SBI(); BOI boi =new BOI(); System.out.println (" SBIInterest "+ sbi.getRateOfInterest ()); System.out.println ("BOI Interest"+ boi.getRateOfInterest ()); } } Output: SBI INTEREST:3 BOI INTEREST:4   class Bank{ int getRateOfInterest() { return 0; } } class SBI extends Bank{ int getRateOfInterest(){ return 3; } } class BOI extends Bank{ int getRateOfInterest(){ return 4; } }

Method Overloading Vs Method Overriding Method Overloading Method Overriding Method overloading is performed within class. Method overriding occurs in two classes that have IS-A relationship. In Method Overloading, parameter must be different. In Method Overriding, parameter must be same. Return type can be same or different in method overloading Return type must be same in method overriding Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its superclass. Method overloading is the example of compile time polymorphism Method overriding is the example of run time polymorphism

Method Overloading Method Overriding class Overloadingexample { int add(int a, int b) { return a+b ; } int add(int a,int b, int c) { return a+b+c ; } } class Animal { void eat() { System.out.println (“ eating”); } } class Dog { void eat() { System.out.println (“flush eating animal”); } }

Dynamic Method Dispatch Dynamic Method Dispatch is the process by which a call to an overridden method is resolved at run time (during code execution). The concept of method overriding is the way to attain runtime polymorphism in java. During the code execution, JVM decides which implementation of the same method should be called. Dynamic Method Dispatch is another name for Runtime Polymorphism.

Abstract Class A class that is declared with the abstract keyword is known as abstract class in java. It can have abstract and non-abstract methods . An abstract method is a method that is declared without any implementation. Abstract class needs to be extended and its method implemented. Abstract class cannot be instantiated (i.e., Object cannot be created for an abstract class).

Abstract Class-Syntax abstract class <class name> { //abstract method and non-abstract methods } Abstract Method Syntax: abstract return type method name(parameter list); Abstract Method: A method which is declared as abstract and does not have implementation is known as an abstract method

Final with Inheritance In Java, the final keyword  is used to restrict the user. The java final keyword can be used in many context.  Final variables:  When a variable is declared as final, its value cannot be changed once it has been initialized. This is useful for declaring constants or other values that should not be modified. Final methods : When a method is declared as final, it cannot be overridden by a subclass. Final classes:  When a class is declared as final, it cannot be extended by a subclass.

Final Variable When a variable is declared as final, its value cannot be changed once it has been initialized. This is useful for declaring constants or other values that should not be modified. class Bike { final int speedlimit=90; //final variable void run() { speedlimit=400; //value cannot be changed System.out.println(“Speedlimit is”+Speedlimit); } } class Test { Public static void main(String args []) { Bike b =new Bike(); b.run(); } }

Using Final to prevent Inheritance When a class is declared as final then it cannot be subclassed i.e. no other class can extend it. This is particularly useful, for example, when creating an immutable class like the predefined String class. Declaring a class as final implicitly declares all of its method as final. final class A { // methods and fields } // The following class is illegal. class B extends A { // ERROR! Can't subclass A }

Using Final to prevent Overriding When a method is declared as final then it cannot be overridden by subclasses. For example, The Object class does this, a number of its methods are final. class A { final void msg() { System.out.println(“This is final method”); } } class B extends A { void msg() { // can’t Override final method in subclass } }

Packages and Interfaces: Packages A package is a collection of similar types of sub-packages, interfaces and classes. In java, there are two types of packages: i ) Built-in Packages ii) User-defined Packages package keyword is used in java to create packages: Syntax: package package-name;

Built-in Packages These packages consist of a large number of classes which are a part of java API. Commonly used packages are java.lang package contains language support classes (which defines primitive types, math operations). This package is automatically imported. java.io package contains classes for supporting input/output operations java.util package contains utility classes like Scanner, Date/Time etc..

Built-in Packages 4) java.applet package contains classes for creating Applets. 5) java.awt package contains classes for implementing the components for GUI like button, menus etc., 6) java.net package contain classes for supporting network operations

User defined Packages User defined packages are those that developers create to incorporate different needs of applications. In Simple terms, User-defined packages are those that the user defines.

Sub Package Packages that are defined inside another package is called subpackage. These are not imported by default, they have to imported explicitly. Example: import java.util.*; Here, util is a sub-package created inside java package.

Packages and Member Access Members of Java private default protected public class N Y N Y variable Y Y Y Y method Y Y Y Y constructor Y Y Y Y interface N Y N Y

Packages and Member Access Access Modifier within class within package outside package by subclass only outside package private Y N N N default Y Y N N protected Y Y Y N public Y Y Y Y

Private-Access Specifier The Private access modifier is accessible only within the class. It cannot be accessed from outside the class. Example: Create two classes A and Simple . The class A contains private data member and private method. When accessing these private members from outside the class (i.e. Simple) , compile-time error will occur.

Example Program-Private Access Specifier   public class  Simple {     public static void  main(String  args []) {       A obj=new A();   //Compile Time Error      System.out.println( obj.data ); obj.msg(); //Compile Time Error       }   }  class  A {   private  int  data= 40 ;   private  void  msg() { System.out.println( "Hello java" ); }   }

Default-Access Specifier The default modifier is accessible only within package. It cannot be accessed from outside the package . It provides more accessibility than private. But, it is more restrictive than protected, and public. If no access modifier is specified, then it is treated as default modifier

Default-Access Specifier   //save by B.java   package  mypack;   import  pack.*;   class  B {      public static void  main(String  args []) {   A obj= new A(); //Compile Time Error    obj.msg(); //Compile Time Error    }   }   //save by A.java   package  pack;   class  A {   v oid msg() { System.out.println( "Hello" ); }   }  In this program, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

Protected -Access Specifier   //save by B.java   package  mypack;   import  pack.*;   class  B extends A {      public static void  main(String  args []) {   B obj= new B ();  obj.msg();  }   }     //save by A.java   package  pack;   public class A {   protected void msg() { System.out.println("Hello"); }   }   The protected access specifier  is accessible within package and outside the package but through inheritance only. Output: Hello

Public -Access Specifier   //save by B.java   package  mypack;   import pack.*;   class B {     public static void main(String  args []) {   A obj= new A ();  obj.msg();  }   }     //save by A.java   package  pack;   public class A {   public void msg() { System.out.println("Hello"); }   }   The public access specifier  is accessible everywhere. It has the widest scope among all other modifiers. Output: Hello

A dvantages of Packages 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

Importing Packages The import keyword is used to access all members of a package using the following statements. 1. import package.* 2. import package.classname 3. fully qualified name

Interfaces An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface, not method body. It is used to achieve abstraction and multiple inheritance in java.

Syntax-Interfaces interface <interface-name> { //declare constant fields //declare methods that abstract by default }

Interfaces

Interface-Java Program     public static void  main(String args[]) {   A obj = new A(); o bj.print(); }   }  interface   Printable {     int MIN=5;   void print(); } class A implements Printable { public void print() { System.out.println(“value:”+MIN); } OUTPUT: Value: 5

A dvantages of Interfaces Interfaces are used to achieve multiple inheritance. Interfaces can be used to enforce a contract-that is a specification that classes must implement certain methods if they want to use that interface.

References 1. www.javatpoint.com