Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Chap 5

This document discusses inheritance and related concepts in Java. It defines inheritance as a mechanism where a subclass inherits the properties and behaviors of its parent class. It describes subclasses, superclasses, polymorphism, abstract classes, access modifiers, and wrapper classes. It provides examples of inheritance hierarchies and method overriding. It also summarizes the key rules and purposes of these object-oriented programming concepts in Java.

Uploaded by

Atharva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Chap 5

This document discusses inheritance and related concepts in Java. It defines inheritance as a mechanism where a subclass inherits the properties and behaviors of its parent class. It describes subclasses, superclasses, polymorphism, abstract classes, access modifiers, and wrapper classes. It provides examples of inheritance hierarchies and method overriding. It also summarizes the key rules and purposes of these object-oriented programming concepts in Java.

Uploaded by

Atharva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Chapter No.

5 Inheritance
 Inheritance
 Inheritance Hierarchies
 Super Class
 Sub Class
 Polymorphism
 Abstract Classes
 Access Modifiers
 Introduction To Wrapper Classes
 Interfaces
 Inner Classes
 Use Of Final

Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours 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.
Terms used in Inheritance
o Sub Class/Child Class/ Derived Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
o 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.
o 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.
o Example:

Syntax:
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
Example

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);
}
}

Inheritance Hierarchies:
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.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Polymorphism:
 Definition: Polymorphism came from the two Greek words poly means many and morphos means
forms.
 The ability to exist in different forms is called polymorphism. “Polymorphism is the ability of an
object to take on many forms.”
 The most common use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object.
 In Java, Polymorphism can be classified as follows –

 Polymorphism uses those methods to perform different tasks. This allows us to perform a single
action in different ways.
 For example: Assume a superclass called Person that has a method called printName(). Subclasses
of Person could be Student, Employee, Doctor etc. They also have their own implementation of a
printName().
Method Overriding:
 Definition: If subclass (child class) has the same method as declared in the parent class, it
suppresses the execution of base class method by the child class. This process is known as method
overriding.
 Though the methods are same in both the classes, they differ in their implementation.
 For example:
class ABC
{
void fun1() { ….. }
void fun2() { ….. } // Method defined
}
class PQR extends ABC
{
void fun3(){ ….. }
void fun2(){ ….. } // Method defined Again
}
 Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
 Method overriding is an example of Runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. The method must have the same return type as in the parent class.
4. There must be an IS-A relationship (inheritance).
Abstract Classes:
 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).
 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.
i) An abstract class must be declared with an abstract keyword.
ii) It can have abstract and non-abstract methods.
iii) It cannot be instantiated.
iv) It can have constructors and static methods also.
v) It can have final methods which will force the subclass not to change the body of the method.
Example:
abstract class Shape
{
void display()
{
//Non-abstract methods
}
public void abstract draw(); // Abstract methods
}

Access Modifiers:
The keyword which modifies the access or scope of a variable, method, constructor, or class is
known as Access modifier. We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
Access Within Within Outside package Outside
Modifier class package by subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Wrapper Classes:
 The classes which "wrap" the primitive data type into an object of that class are known as
Wrapper Classes.
 Each of Java's eight primitive data types has a class dedicated to it.
 The wrapper classes are part of the java.util package.

 The wrapper classes in java servers two primary purposes.


 To provide a mechanism to ‘wrap’ primitive values in an object so that primitives can do
activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc.
collection.
 To provide an assortment of utility functions for primitives like converting primitive types to
and from string objects, converting to various bases like binary, octal or hexadecimal, or
comparing various objects.
 For example:
int x = 25;
Integer y = new Integer(33);
Autoboxing: Boxing is used to convert primitive data types into corresponding objects.
For e.g. –
int x = 25;
Integer y = new Integer(x); or
Integer y = Integer.valueOf(x);
Unboxing: Unboxing is used to convert the Wrapper class object into corresponding primitive
data types.
For e.g. –
Integer y = new Integer(33);
int x = y.intValue();
Below table lists wrapper classes in Java API with constructor details.
Primitive Wrapper Class Constructor Argument
boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double or String
double Double double or String
long Long long or String
short Short short or String
The most common methods of the Integer wrapper class are summarized in below table.
Method Purpose
parseInt(s) returns a signed decimal integer value equivalent to string s
toString(i) returns a new String object representing the integer i
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as a double
floatValue() returns the value of this Integer as a float
intValue() returns the value of this Integer as an int
shortValue() returns the value of this Integer as a short
longValue() returns the value of this Integer as a long
int compareTo(int i) Compares the numerical value of the invoking object with that of
i.
- Returns 0 if the values are equal.
- Returns a -ve value if the invoking object has a lower value.
- Returns a +ve value if the invoking object has a greater
value.
static int compare(int Compares the values of num1 and num2.
num1, int num2) - Returns 0 if the values are equal.
- Returns a -ve value if num1 is less than num2.
- Returns a +ve value if num1 is greater than num2.
boolean Returns true if the invoking Integer object is equivalent to intObj.
equals(Object Otherwise, it returns false.
intObj)

Interfaces:
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A
class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is similar to a class in the following ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
Declaring Interfaces
The interface can be declared as follows –
Syntax:- For example:
interface <interface_name> interface iface
{ {
//Final and static variables int x=10;
// Abstract methods void Print();
} }
Interfaces have the following properties −
 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.
Implementing Interfaces
A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.
class ABC implements iface
{
public void Print()
{
System.out.println(“I am printing on behalf of interface”);
}
}
Accessing methods of Interfaces:
public static void main(String args[])
{
ABC obj = new ABC();
obj.print();
}

Inner classes:
 In Java, just like methods, variables of a class too can have another class as its member. Writing a
class within another is allowed in Java. The class written within is called the nested class, and the
class that holds the inner class is called the outer class.
 We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
 Additionally, it can access all the members of the outer class, including private data members and
methods.
Syntax:
class Outer_class
{
//code
class Inner_class
{
//code
}
}
Advantage of inner classes:
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the members
(data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Need of Inner class:
 Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.
 If all the class objects are a part of the outer object then it is easier to nest that class inside the
outer class. That way all the outer class can access all the objects of the inner class.
Use of Final:
Final Variables & Methods:
 All methods and variables can be overridden by default in subclasses. To prevent the subclasses
from overriding the methods of the superclass, we can declare them as final using the keyword
final as a modifier.
 For example:
final int N = 10;
final void Display() {…….}
 Making a method final ensures that the functionality defined in this method will never be altered
or changed. Similarly the value of the final variable can never be changed.
 Final variables, behave like class variables and they do not take any space on individual objects of
the class.
Final Classes:
 Sometimes, for security reasons, we may require to prevent a class being further subclassed. A
class that cannot be subclassed is called as final class.
 For example:
final class ABC {…….}
final class PQR extends ABC {…….}
Finalizer Method:
 A Constructor method is used to initialize an object when it is created. This process is known as
Initialization. Similarly, Java supports a concept called Finalization.
 The Java finalize() method of Object class is a method that the Garbage Collector always calls just
before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-
up activity.
 It is used to perform clean-up activity before destroying any object. finalize() method is called
by default for every object before its deletion.
public class Javafinalize
{
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println("end of garbage collection");
}

protected void finalize()


{
System.out.println("finalize method called");
}
}
*****

You might also like