java unit 3 PDF.pdf
Document Details
Uploaded by MerryMannerism
Bharati Vidyapeeth’s Institute of Management Studies & Research
Tags
Full Transcript
Concept and importance of inheritance, is-a relationship, types of inheritance, Polymorphism – function overriding, dynamic method dispatch. Using abstract and final keywords with class declaration, Concept of interface and class. By Ms. Neha Gakhar Inheritan...
Concept and importance of inheritance, is-a relationship, types of inheritance, Polymorphism – function overriding, dynamic method dispatch. Using abstract and final keywords with class declaration, Concept of interface and class. By Ms. Neha Gakhar Inheritance in Java Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass. Java Inheritance Example As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ int 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 salary is:40000 Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example: Single Inheritance Example When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. File: TestInheritance.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }} Output: barking... eating... Multilevel Inheritance Example When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. File: TestInheritance2.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} weeping... barking... eating... Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. File: TestInheritance3.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{ void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }} Output: meowing... eating... Method Overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Usage of Java Method Overriding Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism Rules for Java Method Overriding The method must have the same name as in the parent class The method must have the same parameter as in the parent class. There must be an IS-A relationship (inheritance). Understanding the problem without method overriding Let's understand the problem that we may face in the program if we don't use method overriding. //Java Program to demonstrate why we need method overriding //Here, we are calling the method of parent class with child //class object. //Creating a parent class class Vehicle{ void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike extends Vehicle{ public static void main(String[] args){ //creating an instance of child class Bike obj = new Bike(); //calling the method with child class instance obj.run(); } } Output Vehicle is running Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding. Example of method overriding In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding. //Java Program to illustrate the use of Java Method Overriding //Creating a parent class. class Vehicle{ //defining a method void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike2 extends Vehicle{ //defining the same method as in the parent class void run(){System.out.println("Bike is running safely");} public static void main(String[] args){ Bike2 obj = new Bike2();//creating object obj.run();//calling method } } Output: Bike is running safely A real example of Java Method Overriding Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest. Java method overriding is mostly used in Runtime Polymorphism //Java Program to demonstrate the real scenario of Java Method Overriding where three classes are overriding t he method of a parent class. //Creating a parent class. class Bank{ int getRateOfInterest(){return 0;} } //Creating child classes. class SBI extends Bank{ int getRateOfInterest(){return 8;} } class ICICI extends Bank{ int getRateOfInterest(){return 7;} } class AXIS extends Bank{ int getRateOfInterest(){return 9;} } //Test class to create objects and call the methods class Test2{ public static void main(String args[]){ SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); } } Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9 Polymorphism in Java Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. If you overload a static method in Java, it is the example of compile time polymorphism. Runtime Polymorphism in Java Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. Let's first understand the upcasting before Runtime Polymorphism. Upcasting If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example: Here, the relationship of B class would be: B IS-A A B IS-A I B IS-A Object Since Object is the root class of all classes in Java, so we can write B IS-A Object. Example of Java Runtime Polymorphism In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime. Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism. class Bike{ void run(){System.out.println("running");} } class Splendor extends Bike{ void run(){System.out.println("running safely with 60km");} public static void main(String args[]){ Bike b = new Splendor();//upcasting b.run(); } } Output: running safely with 60km. Java Runtime Polymorphism Example: Bank Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest. Note: This example is also given in method overriding but there was no upcasting. class Bank{ float getRateOfInterest(){return 0;} } class SBI extends Bank{ float getRateOfInterest(){return 8.4f;} } class ICICI extends Bank{ float getRateOfInterest(){return 7.3f;} } class AXIS extends Bank{ float getRateOfInterest(){return 9.7f;} } class TestPolymorphism{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); } } Output: SBI Rate of Interest: 8.4 ICICI Rate of Interest: 7.3 AXIS Rate of Interest: 9.7 Java Runtime Polymorphism Example: Shape class Shape{ void draw(){System.out.println("drawing...");} } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle...");} } class Circle extends Shape{ void draw(){System.out.println("drawing circle...");} } class Triangle extends Shape{ void draw(){System.out.println("drawing triangle...");} } class TestPolymorphism2{ public static void main(String args[]){ Shape s; s=new Rectangle(); s.draw(); s=new Circle(); s.draw(); s=new Triangle(); s.draw(); } } Output: drawing rectangle... drawing circle... drawing triangle... Java final class If you make any class as final, you cannot extend it. Example of final class 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 Abstract class in Java A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). Before learning the Java abstract class, let's understand the abstraction in Java first. Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. Ways to achieve Abstraction There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%) Abstract class in Java A class which is declared as abstract is known as an abstract class. It can have abstract and non- abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Points to Remember 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 constructors and static methods also. It can have final methods which will force the subclass not to change the body of the method. Example of abstract class abstract class A{} Abstract Method in Java A method which is declared as abstract and does not have implementation is known as an abstract method. Example of abstract method abstract void printStatus();//no method body and abstract Example of Abstract class that has an abstract method In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class. abstract class Bike{ abstract void run(); } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } running safely Another example of Abstract class in java File: TestBank.java abstract class Bank{ abstract int getRateOfInterest(); } class SBI extends Bank{ int getRateOfInterest(){return 7;} } class PNB extends Bank{ int getRateOfInterest(){return 8;} } class TestBank{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); b=new PNB(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); }} Rate of Interest is: 7 % Rate of Interest is: 8 % Interface in Java 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. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface. Why use Java interface? There are mainly three reasons to use interface. They are given below. It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling. How to declare an interface? An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface. Syntax: interface { // declare constant fields // declare methods that abstract // by default. } The relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface Java Interface Example In this example, the Printable interface has only one method, and its implementation is provided in the A6 class. 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(); } } Output: Hello Java Interface Example: Drawable In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. 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. File: TestInterface1.java //Interface declaration: by first user interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDr awable() d.draw(); }} Output: drawing circle Java Interface Example: Bank Let's see another example of java interface which provides the implementation of Bank interface. File: TestInterface2.java 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 TestInterface2{ public static void main(String[] args){ Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); }} Output: ROI: 9.15 Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance. 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(); } } Output:Hello Welcome Super Keyword in Java The super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of Java super Keyword super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor. 1) super is used to refer immediate parent class instance variable. We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color);//prints color of Dog class System.out.println(super.color);//prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); }} output black white In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword. 2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. 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(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }} Output: eating... barking... In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local. To call the parent class method, we need to use super keyword. 3) super is used to invoke parent class constructor. The super keyword can also be used to invoke the parent class constructor. Let's see a simple example: class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ super(); System.out.println("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dog(); }} : animal is created dog is created Note: super() is added in each class constructor automatically by compiler if there is no super() or this(). As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement. Another example of super keyword where super() is provided by the compiler implicitly. class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ System.out.println("dog is created"); } } class TestSuper4{ public static void main(String args[]){ Dog d=new Dog(); }} Output: animal is created dog is created Note: super() is added in each class constructor automatically by compiler if there is no super() or this().