0% found this document useful (0 votes)
12 views14 pages

Java Chapter 4

The document provides an overview of inheritance in Java, explaining its significance in object-oriented programming, including concepts like single, multilevel, and hierarchical inheritance. It discusses the use of interfaces to achieve multiple inheritance and introduces key terms such as superclass, subclass, and method overriding. Additionally, it covers the super keyword, abstract and final classes, and the Object class, highlighting their roles in Java inheritance and polymorphism.

Uploaded by

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

Java Chapter 4

The document provides an overview of inheritance in Java, explaining its significance in object-oriented programming, including concepts like single, multilevel, and hierarchical inheritance. It discusses the use of interfaces to achieve multiple inheritance and introduces key terms such as superclass, subclass, and method overriding. Additionally, it covers the super keyword, abstract and final classes, and the Object class, highlighting their roles in Java inheritance and polymorphism.

Uploaded by

sujalshrestha9272
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
nit — 4 Inheritan P; Hr: Inheritance |s an important pillar of OOP (Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features (fields and methods) of another class. The process by which one class acquires the properties (data members) and functionalities(methods) of another class is called inheritance. The zim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. 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. Inheritance is used in java for the following: © For Method Overriding (so runtime polymorphism can be achieved). © For Code Reusability. Terms used in Inheritance 9 Class: A class isa group of objects which have common properties. itis 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. Itis 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. 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. Prepared by: Raju Poudel [MCA] 38 ah [cass | Mal Lover nherIance Paap) [cusse | [cise] Hierarchical inheritance [crassa ] [cass | Multiple Inheritance [cass | Class A 1. Single Inheritance public class A { public class B {.. ) public class C extends AB { Java does not support mutiple Inheritance ‘Single Inheritance refers to a child and parent class relationship where a class extends the another class. cla! Animal{ void eat(){ [Link]("“eating, + + class Dog extends Animal{ void bark(){ ‘[Link]("barking.. > + class TestInheritance( public static void main(String argsf1){ Dog d=new Dog(); [Link]( deat(); Prepared by: Raju Poudel [MCA] 39 + + Qutput: barking. eating... Multilevel inheritance Multilevel inheritance refers to a child and parent class relationship where a class extends the child class. For example, class C extends class B and class B extends class A. class Animal{ void eat(){ [Link]("eating. + + class Dog extends Animal{ void bark(){ ‘[Link](“barking.. } } class BabyDog extends Dog{ void ween(){ ‘[Link]("weeping. + "i , class TestInheritance2{ public static void main(String args{]){ BabyDog d=new BabyDog(); [Link](); [Link]();, deat(); + + Output weeping... barking. eating... Prepared by: Raju Poudel [MCA] 40 3. Hierarchical Inheritance Hierarchical inheritance refers to a child and parent class relationship where more than one classes extends the same class. For example, classes B, C & D extends the same class A. class Animal{ void eat(){ [Link](“eating. + } class Dog extends Animal{ void bark(){ ‘[Link]("barking..."); , + class Cat extends Animal{ void meow(){ ‘[Link]("meowing... } ? class TestInheritance3{ public static void main(String args{]){ Cat c=new Cat(); cmeow(); ceat(); /[[Link]();_ //Error //To access property of class Dog create object of class Dog Dog d=new Dog(); [Link]();, + > Output weeping. barking... eating Multiple Inheritance ‘When one class extends more than one classes then this is called multiple inheritance. For ‘example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn’t allow multiple inheritance. We can use interfaces instead of classes to achieve the same purpose. Prepared by: Raju Poudel [MCA] a Interface in Java Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body). % Interfaces specify what a class must do and not how. It is the blueprint of the class. % An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move (). So it specifies a set of methods that the class has to implement. % Ifa dass implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract. ‘Syntax interface { // declare constant fields // declare methods that abstract // by default. To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the methods in interface are declared with empty body and are public and all fields are public, static and final by default. A class that implement interface must implement all the methods declared in the interface. To implement interface use implements keyword. Why do we use interface? ‘+ Itis used to achieve total abstraction. + Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance. // ® simple interface interface Player ( final int id = 10; int move() Prepared by: Raju Poudel [MCA] 42 Example of Interface // Java program to demonstrate working of // interface. import [Link].*; // & simple interface interface inl { // public, static and final final int a = 10; // public and abstract void display(); + // A class that implements interface. class testClass implements inl { // Implementing the capabilities of // interface. public void display() { [Link].print1n("Geek"); + // Driver Code public static void main (String[] args) { testClass t = new testClass(); [Link](); [Link].print1n(a, } t Output: Geek 10 Prepared by: Raju Poudel [MCA] 43 Use of Interface to achieve multiple inheritance Let us say we have two interfaces A & B and two classes C & D. Then we can achieve multiple inheritance using interfaces as follows: interface A{ } interface B{ } class C{ } class D extends C implements A.B { } Example Program interface interfacel{ void display1(); } interface interface2{] void display2(); class A{ void display3() { ‘[Link]("I am inside class"); + } class B extends A implements interface1, interface2{ public void display1() { [Link]("I am inside interfacei"); t public void display2() { [Link]("I am inside interface2"); t t public class Multilevel { public static void main(String[] args) { obj.display1(); obj.display2(); obj. display3();| Output I am inside interface1 I am inside interface2 I am inside class Prepared by: Raju Poudel [MCA] 4a Another Example interface interfacel{ int a=20,b=10; void add(); + class Ax{| int diff; > void subtract(int x,int y) { diffox-y; Systen. out.print1n("Subtractior “edi ff) 5 class Bx extends Ax implements interfacel{ ant sum; > public void add() { sum=a+b; System. out. printIn("Addition= +sum) 5 t public class Multilevel { public static void main(String[] args) { Bx obj=new Bx(); [Link]() 5 obj. subtract (50, [1d);| } t Output Addition= 30 Subtraction= 4@ Prepared by: Raju Poudel (MCA] 4s Dynamic Method Dispatch Method overriding forms the basis for one of Java's most powerful concepts: 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. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Here is an example that illustrates dynamic method dispate! // Dynamic Method Dispatch class A { void callme() { [Link]("Inside A's callme method") ; ) ) class B extends A { // override callne() void callme() { [Link]("Inside B's callme method") ; , } class C extends A { // override caline() void callme() { [Link] .printIn("Inside C's callme method") ; ) ) class Dispatch { public static void main(String args(}) { A a= new A(); // object of type A Bb = new B(); // object of type B Cc = new C(); // object of type C Ar; // obtain a reference of type A =a; // © refers to an A object -callme(); // calls A's version of callme r=; // x refers to a B object r-callme(); // calls B's version of callme r=; // x refers to a C object [Link](); // calls C's version of callme } } ‘The output from the program is shown here: Inside A’s callme method Inside B's callme method Inside C’s callme method Prepared by: Raju Poudel [MCA] 46 This program creates one superclass called A and two subclasses of it, called 8 and C. Subclasses B and C override callme| ) declared in A. Inside the main( ) method, objects of type A, B, and C are declared. Also, a reference of type A, called r, is declared. The program then in turn assigns a reference to each type of object to r and uses that reference to invoke callme{ }. As the output shows, the version of callme{ ) executed is determined by the type of object being referred to at the time of the call. Had it been determined by the type of the reference variable, r, you would see three calls to A’s callme( ) method. Super Keyword The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the following contexts: 1. Use of super with variables: This scenario occurs when a derived class and base class has same data members. in that case there is a possibility of ambiguity for the JVM. We can understand it more clearly using this code snippet: /* Base class vehicle */ class Vehicle { } int maxSpeed = 120; /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print maxSpeed of base class (vehicle) */ [Link].print1n("Maximum Speed: " + [Link]) ; } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car(); small. display(); } Prepared by: Raju Poudel [MCA] a7 In the above example, both base class and subclass have a member maxSpeed. We could access maxSpeed of base class in subclass using super keyword. 2. Use of super with methods: This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to understand the said usage of super keyword. /* Base class Person */ class Person { void message() t [Link]("This is person class"); + } /* Subclass Student */ class Student extends Person { void message() { [Link]("This is student class); , // Note that display() is only in Student class void display() { // will invoke or call current class message() method message()s // will invoke or call parent class message() method [Link](); + } /* priver program to test */ class Test { public static void main(String args[]) { Student s = new Student (); // calling display() of Student [Link](); , + Output This is student class This is person cass In the above example, we have seen thatif we only call method message () then, the current class message () is invoked but with the use of super keyword, message () of superclass could also be invoked. Prepared by: Raju Poudel [MCA] 48 [Link] of super with constructors: super keyword can also be used to access the parent ‘class constructor. One more important thing is that, “super’ can call both parametric as well ‘as non-parametric constructors depending upon the situation. Following is the code snippet to explain the above concept: J* superclass Person */ class Person { Person() { [Link]("Person class Constructor”); t } /* subclass Student extending the Person class */ class Student extends Person { Student() { // invoke or call parent class constructor super(); [Link]("Student class Constructor") 5 } } /* Driver program to test*/ clazs Test { public static void main(String[] args) { Student s = new Student(); } } Output: Person class Constructor Student class Constructor In the above example we have called the superclass constructor using keyword ‘super’ via subclass constructor. Prepared by: Raju Poudel [MCA] 49 Abstract and Final Classes Abstract class has been discussed already in Unit-3 (Abstraction). The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The other two uses of final apply to inheritance. Using final to Prevent Overriding While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final: class A ( final void meth() { [Link] .printin(*This is a final method. *: } ) class B extends A { void meth() { // ERROR! Can't override. [Link] .printia(*Tllegal!*); ) } Because meth () is declared as final, it cannot be overridden in 8. If you attempt to do so, a compile-time error will result. Using final to Prevent Inheritance Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, itis illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. Here is an example of a final class: final class A ( Ws ) // The following class is illegal. class B extends A { // ERROR! Can't subclass A uW } As the comments imply, it is illegal for B to inherit A Since A is declared as final. Prepared by: Raju Poudel [MCA] 50 The Object Class There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array. Object defines the following methods, which means that they are available in every object. ‘Method Purpose object clonet ) Creates a new object that is the same as the object being cloned. [boolean equais(Opject onject) [Determines wnetner one object 1S equal to another. void finalize ) [Called before an unused object is recycled. [Class getClass( ) Obtains the class of an object at run time. int hashCode ) [Retums the hash code associated with the invoking object. void notify) Resumes execution of a thread waiting on the invoking object. oid notifyAll) Resumes execution of all threads waiting on the invoking object. | string tostring( ) [Retums a string that describes the object. oid wait) |Waits on another thread of execution. void wait(iong milliseconds) oid waittong milliseconds. int nanoseconds) The methods getClass( ), notify( }, notifyall( ), and wait( ) are declared as final. You may ‘override the others. However, notice two methods now: equals( ) and toString( ). The ‘equals( ) method compares the contents of two objects. It returns true if the objects are equivalent, and false otherwise. Package ‘A java package is 2 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. There are many built-in packages such as java, lang, awt, javax, swing, net, io, uti, sql etc. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. The package keyword is used to create a package in java. Jisave as [Link] package mypack; public class Simple{ public static void main(String args{1){ [Link]("Welcome to package"); > + Prepared by: Raju Poudel [MCA] si

You might also like