0% found this document useful (0 votes)
18 views26 pages

MODULE-II MR-23 Java Inhertance and Packages

Uploaded by

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

MODULE-II MR-23 Java Inhertance and Packages

Uploaded by

shivakumark4648
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

MODULE-II

Inheritance and Packages


Inheritance in Java
 Inheritance in Java is the method to create a hierarchy between
classes by inheriting from other classes.

 Java, Inheritance is an important pillar of OOP(Object-Oriented


Programming).

 In Java Inheritance means creating new classes based on existing


ones.

 Java inheritance using are code re-usability, method overriding and


abstractions.

 Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

How to Use Inheritance in Java?


 The extends keyword is used for inheritance in Java.

 The extends keyword indicates you are derived from an existing


class.

 In other words, “extends” refers to increased functionality of classes.

 In the terminology of Java, a class which is inherited is called a parent


or superclass, and the new class is called a child or subclass.

The Syntax of Inheritance in Java :

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }
Example for Inheritance :

Hear Programmer is the subclass and Employee is the superclass.

Example: Write java program how to create inheritance.

class Employee // create a super class or base class


{
float salary=40000;
}
class Programmer extends Employee // create a sub class or child class
{
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);
}
}
OUTPUT:

Programmer salary is:40000.0


Bonus of programmer is:10000
Types of Inheritance in Java

There are five different types of inheritance in java programming


language. They are

1. Single Level Inheritance


2. Multi Level Inheritance
3.Hierarchal Inheritance
4. *Multiple Inheritance
5. Hybrid Inheritance

Note: In java programming, multiple inheritances is supported through


interface only. Doesn’t support directly in java class.

1. Single-Level Inheritance :
When a class inherits another class, it is known as a single inheritance.

Dog class (Sub class) inherits to the Animal class (Super class), so it is called

a single inheritance.

Example:- Write a java program how to create a single level inheritance.

1. class Animal // To a create a super class


2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal// To a create a sub class
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class SingleInheritance
16. {
17. public static void main(String args[])
18. {
19. Dog d=new Dog();
20. d.bark();
21. d.eat();
22. }
23. }

2. Multi-Level Inheritance :

When there is a chain of inheritance, it is known as multilevel inheritance.


Example 2: Write java program how to create multilevel Inheritance

Import java.io.*;
1. class cse // Create a Super class
2. {
3. void csed()
4. {
5. System.out.println("Computer Science and Engineering Branch...");
6. }
7. }
8. class AIML extends cse // Create a sub-class1
9. {
10. void aimlmd()
11. {
System.out.println("AI&ML Branch...");
12. }
13. }
14. class DS extends AIML // Create s sub-class2
15. {
16. void dsd()
17. {
18. System.out.println("Data Science Branch...");
19. }
20. }
21. class CS extends DS // Create a sub class-3
22. {
23. void csd()
24. {
25. System.out.println (“ Cyber Security Branch….”);
26. }
27. }
28. Class IOT extends CS // Create sub class-4
29. {
30. void iotd()
31. {
32. System.out.println (“ Internet of Things Branch….”);
33. }
34. }
35. class mreca
36. {
37. public static void main(String args[])
38. {
39. IOT i=new IOT();
40. i.csed();
41. i.aimlmd();
42. i.dsd();
43. i.csd();
44. i.iotd();
45. }
46. }

3. Hierarchal Inheritance :
When two or more classes inherit a single class, it is known as hierarchical
inheritance.

Example : Hierarchal Inheritance class B, C and D extends a same class A.

Write a java program how to implement hierarchal Inheritance.

import java.io.*;
1. public class cse // Create a super class
2. {
3. void csed()
4. {
5. System.out.println("Computer Science and Engineering...");
6. }
7. }
8. public class aiml extends cse // Create a sub class-1
9. {
10.void aimlmd()
11.{
12.System.out.println("Artificial Intelligence and Machine Leraning...");
13.}
14.}
15.public class ds extends cse // Create a sub class-2
16.{
17.void dsd()
18.{
19.System.out.println("Data Science Engineering...");
20.}
21.}
22.Public class iot extends cse // Create a sub class-3
23. {
24.void iotd()
25.{
26.System.out.println (“ Intertet of Things Department”);
27.}
28.public class mrec {
29.
30.public static void main(String args[])
31.{
32.iot i=new iot();
33.i.csed();
34.i..aimlmd();
35.i.dsd();
36.i.iotd();
37.}
38.}

5.Hybrid Inheritance :

 The meaning of hybrid (mixture) is made of more than one thing.


 In Java, the hybrid inheritance is the composition of two or more
types of inheritance.
 The main purpose of using hybrid inheritance is to modularize the
code into well-defined classes.
 It also provides the code reusability.
Write a java program how to create hybrid inheritance

1. class GrandFather // Create a Super Class


2. {
3. public void showG()
4. {
5. System.out.println("He is grandfather.");
6. }
7. }
8. class Father extends GrandFather // Create a Sub class 1
9. {
10.public void showF()
11.{
12.System.out.println("He is father.");
13.}
14.}
15.class Son extends Father // Create a Sub-class 2
16.{
17.public void showS()
18.{
19.System.out.println("He is son.");
20.}
21.}
22.public class Daughter extends Father // Create Sub-class 3
23.{
24.public void showD()
25.{
26.System.out.println("She is daughter.");
27.}
28.public static void main(String args[])
29.{
30.Son obj1 = new Son();
31.obj1.showS(); // Accessing Son class method
32.obj1.showF(); // Accessing Father class method
33.obj1.showG(); // Accessing GrandFather class method
34.Daughter obj2 = new Daughter();
35.obj2.showD(); // Accessing Daughter class method
36.obj2.showF(); // Accessing Father class method
37.obj2.showG(); // Accessing GrandFather class method
38.}
39.}

OUTPUT:

He is son.
He is father.
He is grandfather.
She is daughter.
He is father.
He is grandfather.

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

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Example: Write java program how to create inheritance using


super key word.

1. class Animal { // Create a super class


2. String color="white";
3. }
4. class Dog extends Animal { // Create a sub class
5. String color="black";
6. void printColor()
7. {
8. System.out.println(color);
9. System.out.println(super.color); // Using a super key word
10. }
11. }
12. class cse
13. {
14. public static void main(String args[])
15. {
16. Dog d=new Dog();
17. d.printColor();
18. }
19. }
final Keyword in Java :
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. final key word can be used
followings are

A) final variable declartion

B) final method declartion

C) final class declation


A). Java final variable :
 If you make any variable as final, you cannot change the value of
final variable,

 It will be constant variable can not chage.

 It will be use final key word in three types are

Example : write java program how to use final variable.

1. class Bike{
2. final int speedlimit=90; // Use a final variable
3. void run() {
4. speedlimit=400;
5. }
6. public static void main(String args[])
7. {
8. Bike obj=new Bike();
9. obj.run();
10. }
11. }

B). Java final method :


If you make any method as final, you cannot override it.

Example : Write a java program how to use a final method.


1. class Bike{
2. final void run() // Use a final method
3. {
4. System.out.println("running");
5. }
6. }
7. class Honda extends Bike
8. {
9. void run()
10. {
11. System.out.println("running safely with 100kmph");
12. }
13. public static void main(String args[])
14. {
15. Honda honda= new Honda();
16. honda.run();
17. }
18. }
C). Java final class : If you make any class as final, you cannot extend
it.

Example : Write a java program how to use a final class.

final class Bike{} // Use a final class to declared only super class

1. class Honda1 extends Bike {


2. void run()
3. {
4. System.out.println("running safely with 100kmph");
5. }
6. }
7. class cse {
8. public static void main(String args[])
9. {
10. Honda1 honda= new Honda1();
11. honda.run();
12. }
13. }
Base Class Object or Object class in Java :

The Object class in java is the parent class of all the classes in java by
default.

It is the top most class of java.


Examples:

Son obj1 = new Son();


Daughter obj2 = new Daughter();

Sub class in java :

 A class (super class) that is derived from another class is called a


subclass It is also called a derived class or child class.

 It is using extends keyword for creating another sub class or child


class to existing super class.

Example:

class course { // Create Super class

csem()
{
// statements and fields
}
class AIML extends coures { // Create a sub class

aiml()
{
//Statements and fields
}
class mreca
{
AIML a= new AIML();
a. csem();
a. aiml();
}
}

Sub type in java :

 Sub typing in java is a key feature of object-oriented languages such


as Java.

 In Java, one type (super class) is a subtype of another class (sub class)
using extends keyword to implement into inheritance..

Sustainability in java :

The sustainability in java is a when a child class acquires properties from


its parent class, the object of the parent class may be substituted with the
child class object.

Example: Dog class (Sub class) inherits to the Animal class (Super class),
so it is called a sustainability in java.

Java Forms of Inheritance :


The following are the different forms of inheritance in java.

 Specialization
 Specification
 Construction
 Eextension
 Limitation
 Combination

 Specialization
It is the most ideal form of inheritance. The subclass is a special case of
the parent class. It holds the principle of substitutability.

 Specification
This is another commonly used form of inheritance. In this form of
inheritance, the parent class just specifies which methods should be
available to the child class but doesn't implement them. The java provides
concepts like abstract and interfaces to support this form of inheritance. It
holds the principle of substitutability.

 Construction
This is another form of inheritance where the child class may change the
behavior defined by the parent class (overriding). It does not hold the
principle of substitutability.

 Eextension
This is another form of inheritance where the child class may add its new
properties. It holds the principle of substitutability.

 Limitation
This is another form of inheritance where the subclass restricts the
inherited behavior. It does not hold the principle of substitutability.

 Combination
This is another form of inheritance where the subclass inherits properties
from multiple parent classes. Java does not support multiple inheritance
type.

Benefits of Inheritance :
 Inheritance helps in code reuse. The child class may use the code
defined in the parent class without re-writing it.
 Inheritance can save time and effort as the main code need not be
written again.
 Inheritance provides a clear model structure which is easy to
understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base
class so that the meaningful implementation of the base class method
can be designed in the derived class.
 In inheritance base class can decide to keep some data private so that
it cannot be altered by the derived class.

Costs of Inheritance :
 Inheritance decreases the execution speed due to the increased time
and effort it takes, the program to jump through all the levels of
overloaded classes.
 Inheritance makes the two classes (base and inherited class) get
tightly coupled. This means one cannot be used independently of each
other.
 The changes made in the parent class will affect the behavior of child
class too.
 The overuse of inheritance makes the program more complex.

Member Access Rules :

 The Member Access Modifiers in Java specifies the accessibility or


scope of a field, method, constructor, or class.

 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.

Method Overriding in Java :

 The method overriding is the process of re-defining a method in a


child class that is already defined in the parent class.
 When both parent and child classes have the same method, then that
method is said to be the overriding method.
 The method overriding is also known as Dynamic Method
Dispatch or Run- time Polymorphous or Pure Polymorphous.

Method Overriding Rules :

 Static methods can not be overridden.


 Final methods can not be overridden.
 Private methods can not be overridden.
 Constructor can not be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent
has it.

Example : Write a java program to create a inheritance using


method overriding.

class ParentClass{
int num = 10;
void showData() // Create Method Overrding
{
System.out.println("Inside ParentClass show method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass
{
void showData() // Create Method Overriding
{
System.out.println("Inside ChildClass show method");
System.out.println("num = " + num);
}
}
class cse {
public static void main(String[] args)
{
ParentClass obj = new ParentClass(); // Object create a super class
obj.showData(); // Call a method Super Class
obj = new ChildClass(); // Object create a same super class
obj.showData(); // Calla a method sub-class
}
}

Java Abstract Classes and Abstract Method

 An abstract class is a class that created using abstract keyword. In


other words, a class prefixed with abstract keyword is known as an
abstract class.
 In java, an abstract class may contain abstract methods (methods
without implementation) and also non-abstract methods (methods
with implementation).

Rules for abstract class:-


 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

1. abstract class A{
2. // Statements and fields
3. }

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

Example1 : Write a java program how to create abstract class

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda extends Bike{
5. void run()
6. {
7. System.out.println("running safely");
8. }
9. class cse {
10. public static void main(String args[])
11. {
12. Bike obj = new Honda();
13. obj.run();
14. }
15. }

Example 2 : Write a java program to find the area of rectangle, area


of triangle and area of the radius using abstract class
with inheritance.
import java.util.*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea()
{
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape {
void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class abcse
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}

Java Object class :


 In java, the Object class is the super most class of any class hierarchy.
The Object class in the java programming language is present inside
the java.lang package.
 Every class in the java programming language is a subclass of Object
class by default.

Methods of Object class

The following table depicts all built-in methods of Object class in java.

Method Description

getClass() Returns Class class object

hashCode() returns the hashcode number for object being used.

equals(Object obj) compares the argument object to calling object.


Method Description

clone() Compares two strings, ignoring case

concat(String) Creates copy of invoking object

toString() eturns the string representation of invoking object.

notify() wakes up a thread, waiting on invoking object's monitor.

notifyAll() wakes up all the threads, waiting on invoking object's monitor.

wait() causes the current thread to wait, until another thread notifies.

wait(long,int) causes the current thread to wait for the specified milliseconds
and nanoseconds, until another thread notifies.

finalize() It is invoked by the garbage collector before an object is being


garbage collected.

Java Packages
 A java package is a group of similar types of classes, interfaces and
sub-packages.
 Packages in java can be categorized in two types are

1. Built-in packages
2. User-defined packages.

1. Built-in packages :- There are many built-in packages such as java,


io, util, lang, awt, javax, swing, net, io, util, sql, applet etc.

2. User-defined packages:- Users can a own defining, creating and


accessing a new packages.

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.

2. User defined packages : Users can a own defining, creating and


accessing a new packages.

Example: The package keyword is used to create a package in java.

Example : Write java program how to create a user defined


package.

1. package mypack;
2. public class Simple{
3. public static void main(String args[])
4. {
5. System.out.println("Welcome to package");
6. }
7. }

Example 2: Write a java program to create a user defined package


to display message is “ Hello!”

1. package pack;
2. public class A
3. {
4. public void msg()
5. {
6. System.out.println("Hello");
7. }
8. }
Import Packages
The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example :- Write a java progra how to implement import package.

package pack; // User Define Package Declartions


public class A // Create class A
{
public void msg() // Create a Java Method
{
System.out.println("Hello ! How are you?");}
}
package mypack; // User Define another Package Declartions
import pack.*;
public class B // Create class B another package
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello! How are you?

Understanding CLASSPATH in Java


CLASSPATH is actually an environment variable in Java, and tells Java
applications and the Java Virtual Machine (JVM) where to find the
libraries of classes.

Importance of CLASSPATH in Java :


 These include any that you have developed on your own java
programs.

 A CLASSPATH is a file directory on your computer.

 If you need to install a programming language, you might need to put


it in your system PATH variable.

 The build system uses the classpath to locate and load classes and
libraries required for the build process.

 All the directories which contain .class files and JAR files (Java
Archive File) files or zip files when setting the CLASSPATH.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy