0% found this document useful (0 votes)
6 views

JavaUNIT 3 (1)

Imp

Uploaded by

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

JavaUNIT 3 (1)

Imp

Uploaded by

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

UNIT 3 : Inheritance, Interface and Package

3.1 Inheritance
 It is the mechanism in Java by which one class is allowed to inherit the features(fields
and methods) of another class.

 Important Terminologies Used in Java Inheritance


1. Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes.
2. Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
3. Sub Class/Child Class: The class that inherits the other class is known as a subclass(or
a derived class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
4. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class.

 How to Use Inheritance in Java?


 The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to
increased functionality.

 Syntax :
class derived-class extends base-class
{
//methods and fields
}
 Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below,
class A serves as a base class for the derived class B.
import java.io.*;

import java.lang.*;

import java.util.*;

class One {

public void print()

System.out.println("I");

class Two extends One

public void print_for()

System.out.println("Love Java");

public class Main

public static void main(String[] args)

Two g = new Two();

g.print();

g.print_for();

}
2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts
as the base class for other classes.

import java.io.*;

import java.lang.*;

import java.util.*;

class One {

public void print1()

System.out.println("I");

class Two extends One {

public void print2()

System.out.println("Love");

class Three extends Two {

public void print3()

System.out.println("Java");
}

public class Main {

public static void main(String[] args)

Three g = new Three();

g.print1();

g.print2();

g.print3();

3. Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the
below image, class A serves as a base class for the derived classes B, C, and D.

class A {

public void print_A() { System.out.println("Class A"); }

class B extends A {

public void print_B() { System.out.println("Class B"); }

class C extends A {

public void print_C() { System.out.println("Class C"); }

}
class D extends A {

public void print_D() { System.out.println("Class D"); }

public class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B.
Syntax
class MyClass implements Interface1, Interface2, Interface3
{
// class body
}

import java.io.*;

import java.lang.*;

import java.util.*;

interface One {

public void print1();

interface Two {

public void print2();

interface Three extends One, Two {

public void print3();

class Child implements Three {

System.out.println("Java");

public void print_for() { System.out.println("Is Simple"); }

// Drived class

public class Main {

public static void main(String[] args)

Child c = new Child();

c.print1();

c.print2();

c.print3();

}
}

5. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances
with classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can
achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.

The hybrid inheritance can be achieved by using the following combinations:

 Single and Multiple Inheritance (not supported but can be achieved through interface)
 Multilevel and Hierarchical Inheritance
 Hierarchical and Single Inheritance
 Multiple and Multilevel Inheritance

class HumanBody

public void displayHuman()

System.out.println("Method defined inside HumanBody class");

interface Male

public void show();

interface Female
{

public void show();

public class Child extends HumanBody implements Male, Female

public void show()

System.out.println("Implementation of show() method defined in interfaces Male and Female");

public void displayChild()

System.out.println("Method defined inside Child class");

public static void main(String args[])

Child obj = new Child();

System.out.println("Implementation of Hybrid Inheritance in Java");

obj.show();

obj.displayChild();

Method Overloading and Method Overriding:

Method Overloading Method Overriding


1. Method overloading is a compile-time 1. Method overriding is a run-time
polymorphism. polymorphism.
2. It occurs within the class. 2. It is performed in two classes with
inheritance relationships.
3. Method overloading may or may not require 3. Method overriding always needs inheritance.
inheritance.
4. In method overloading, methods must have 4. In method overriding, methods must have the
the same name and different signatures. same name and same signature
5. Static binding is being used for overloaded 5. Dynamic binding is being used for overriding
methods. methods.
6. Private and final methods can be overloaded. 7. Private and final methods can’t be
overridden.
8. The argument list should be different while 9. The argument list should be the same in
doing method overloading. method overriding.
Example Of Method Overloading Example Of Method Overriding
import java.io.*;
import java.io.*;
class MethodOverloadingEx {
// Base Class
static intadd(int a, int b) { return a + b; } class Animal {
void eat()
static intadd(int a, int b, int c) {
{ System.out.println("eat() method of base class");
return a + b + c; System.out.println("eating.");
} }
}
// Main Function
public static void main(String args[]) // Inherited Class
{ class Dog extends Animal {
System.out.println("add() with 2 parameters"); void eat()
// Calling function with 2 parameters {
System.out.println(add(4, 6)); System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
System.out.println("add() with 3 parameters"); }
// Calling function with 3 Parameters }
System.out.println(add(4, 6, 7));
} class MethodOverridingEx {
} // Main Function
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();

d1.eat();
a1.eat();

Animal animal = new Dog();


// eat() method of animal class is overridden by
// base class eat()
animal.eat();
}
}

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept
of having more than one constructor with different parameters so that every constructor can perform a different
task.

public class Student {

//instance variables of the class

int id;

String name;

Student(){

System.out.println("this a default constructor");


}

Student(inti, String n){

id = i;

name = n;

public static void main(String[] args) {

//object creation

Student s = new Student();

System.out.println("\nDefault Constructor values: \n");

System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");

Student student = new Student(10, "David");

System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);

Dynamic Method Dispatch or Runtime Polymorphism in Java


When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object
being referred to at the time the call occurs. Thus, this determination is made at run time.

class A

void m1()

System.out.println("Inside A's m1 method");

class B extends A
{

// overriding m1()

void m1()

System.out.println("Inside B's m1 method");

class C extends A

// overriding m1()

void m1()

System.out.println("Inside C's m1 method");

// Driver class

class Dispatch

public static void main(String args[])

// object of type A

A a = new A();

// object of type B

B b = new B();

// object of type C

C c = new C();

// obtain a reference of type A

A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()

ref.m1();

// now ref refers to a B object

ref = b;

// calling B's version of m1()

ref.m1();

// now ref refers to a C object

ref = c;

// calling C's version of m1()

ref.m1();

final Keyword in Java


The final method in Java is used as a non-access modifier applicable only to a variable, a method, or
a class. It is used to restrict a user in Java.

The following are different contexts where the final is used:

1. Variable

2. Method

3. Class
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. This is useful for
methods that are part of a class’s public API and should not be modified by subclasses.

Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for classes
that are intended to be used as is and should not be modified or extended.

Use of Super Keyword


 Use of super with Variables
 Use of super with Methods
 Use of super with Constructors
1. Use of super with Variables
This scenario occurs when a derived class and base class have the same data members. In that case,
there is a possibility of ambiguity r the JVM.
2. Use of super with Methods

This is used when we want to call the parent class method. So whenever a parent and child class have the same-
named methods then to resolve ambiguity we use the super keyword.

3. Use of super with constructors

The 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 on the situation.

Abstract Methods in Java


Sometimes, we require just method declaration in super-classes. This can be achieved by specifying the abstract
type modifier. These methods are sometimes referred to as subclasser responsibility because they have no
implementation specified in the super-class.

abstract type method-name(parameter-list);


Abstract Classes in Java
The class which is having partial implementation(i.e. not all methods present in the class have method
definitions). To declare a class abstract, use this general form :

abstract class class-name{


//body of class
}

Static Keyword In Java


The static keyword in Java is mainly used for memory management. The static keyword in
Java is used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes. The static keyword belongs to
the class than an instance of the class. The static keyword is used for a constant variable or a
method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the following:
1. Blocks
2. Variables
3. Methods
4. Classes
1. Static variables
When a variable is declared as static, then a single copy of the variable is created and shared
among all objects at the class level. Static variables are, essentially, global variables. All
instances of the class share the same static variable.
2. Static methods
When a method is declared with the static keyword, it is known as the static method. The
most common example of a static method is the main( ) method. As discussed above, Any
static member can be accessed before any objects of its class are created, and without
reference to any object.
3. Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-level class with
a static modifier but can declare nested classes as static. Such types of classes are called
Nested static classes. Nested static class doesn’t need a reference of Outer class.

Interface In Java
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction and
multiple inheritances in Java using Interface. In other words, you can say that interfaces can
have abstract methods and variables. It cannot have a method body.

Syntax for Java Interfaces


interface interface_name{
// declare constant fields
// declare methods that abstract
// by default.
}

Relationship with Interface With class

1)First Example
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());
}}

2)Second Example (Nested interface)


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

Packages In Java
 Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
 Providing controlled access: protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
 Packages can be considered as data encapsulation (or data-hiding).

1. User Defined Packages


User-defined packages These are the packages that are defined by the user. First we
create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the
package names.
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}

2. Build In Packages:
Built-in Packages These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
eg.
Import java.util.*;
Import java.util.Vector;

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