0% found this document useful (0 votes)
16 views48 pages

Unit 2

The document discusses key concepts in Java programming, including method overloading, inheritance, interfaces, and polymorphism. It explains how to use methods with the same name but different parameters, the advantages of inheritance, and the different types of inheritance such as single, multilevel, and multiple inheritance through interfaces. Additionally, it covers the use of abstract classes, final keywords, and the structure of packages in Java.

Uploaded by

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

Unit 2

The document discusses key concepts in Java programming, including method overloading, inheritance, interfaces, and polymorphism. It explains how to use methods with the same name but different parameters, the advantages of inheritance, and the different types of inheritance such as single, multilevel, and multiple inheritance through interfaces. Additionally, it covers the use of abstract classes, final keywords, and the structure of packages in Java.

Uploaded by

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

UNIT II :

Inheritance, Packages and Interfaces


Overloading Methods
• we can use many methods having the same function name but can
pass different number of parameters or different types of
parameter.

int sum(int a,int b);

double sum(double a, double b);

int sum(int a,int b,int c);


public class OverloadingDemo {
public static void Sum(int num1,int num2)
{ public static void main(String args[]) {
int ans; System.out.println("Sum of two integers");
ans=num1+num2; Sum(10,20);
System.out.println(ans); System.out.println("Sum of two double numbers");
} Sum(10.5,20.4);
public static void Sum(double num1,double num2) System.out.println("Sum of three integers");
{ Sum(10,20,30);
double ans; }}
ans=num1+num2;
System.out.println(ans); Output
} F:\test>javac
public static void Sum(int num1,int num2,int num3) OverloadingDemo.java
{ F:\test>java
int ans; OverloadingDemo
ans=num1+num2+num3; Sum of two integers
System.out.println(ans) 30
} Sum of two double numbers
30.9
Sum of three integers
60
Objects as Parameters
• The object can be passed to a method as an argument.
• Using dot operator the object's value can be accessed.

Rectangle1 obj = new Rectangle1();

obj.area();//call the to method

Rectangle1 obj1 = new Rectangle1(11,20);

obj1.area();//call the to method


Returning Objects
lass ObjRetDemo {

Demo(int val)

Demo fun()

Demo temp = new ObjRetDemo (a+5); //created a new object return temp; //returning the object from this method

bjRet {
tatic void main(String args[])

Demo obj2=new ObjRetDemo (20);


Demo obj1;
bj2.fun();//obj1 gets the value from object temp
out.println("The returned value is = "+obj1.a);

javac ObjRetDemo.java
java ObjRet
urned value is = 25
Static, Nested and Inner Classes

Inner classes are the nested classes.

That means these are the classes that are defined inside the other classes. The syntax of defining the inner class is

Access modifier class OuterClass There are four types of inner classes -
{
//code
1. Static member classes
Access_modifier class InnerClass
{
//code 2. Member classes
}
} 3. Local classes

4. Anonymous classes
1. Static member classes

This inner class is defined as the static member variable of another class.

Access modifier class OuterClass


{
//code
public static class InnerClass
{
//code
}
2. Member classes

This type of inner class is non-static member of outer class

3. Local classes

This class is defined within a Java code just like a local variable.
Syntax

Access_modifier class OuterClass


{
//code
Access_modifier return_type methodname (arguments)
{
class InnerClass
{
//code
}
//code
}
}
4. Anonymous classes class MyInnerClass implements Runnable
{
public void run()
Anonymous class is a local class without any name.
{
•Anonymous class is a one-shot class- created exactly where System.out.println("Hello");
}
needed
class DemoClass
• The anonymous class is created in following situations-santa {
public static void main(String[] arg)
о When the class has very short body.
{
o Only one instance of the class is needed. MyInnerClass my = new MyInnerClass();
Thread th=new Thread(my);
o Class is used immediately after defining it.
my.start();
• The anonymous inner class can extend the class, it can implement }
}
the interface or it can be declared in method argument.
}
Inheritance: Basics

Definition: Inheritance is a mechanism in Java by which derived class can borrow the properties of base class and at the same
time the derived class may have some additional properties.

Advantages of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing
common code amongst several subclasses.
1. Reusability: The base class code can be used by derived class without any need to rewrite the code.
2. Extensibility: The base class logic can be extended in the derived classes.
3. Data hiding: Base class can decide to keep some data private so that it cannot be altered by the derived class.
4. Overriding: With inheritance, we will be able to override the methods of the base class so that meaningful
implementation of the base class method can be designed in the derived class
Inheritance Concept of Base and Derived Class

The inheritance is a mechanism in which the child class is derived from a parent class.

This derivation is using the keyword extends.

parent class is called base class and child class is called derived class.

Class A
This is Base class
{
………
}
Class B extends A
This is Derived class
{
……….// uses properties of A
}
Types of Inheritance

1. Single inheritance : 2. Multiple inheritance : 3. Multilevel inheritance :


Types of Inheritance

4. Hybrid inheritance :
//Super class
Implementation of Different Types of Inheritance
class Vehicle {
Vehicle() {
1. Single inheritance : System.out.println("This is a Vehicle");
}
}

// Subclass
class Car extends Vehicle {
Car() {
System.out.println("This Vehicle is Car");
}
}

public class Test {


public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
Car obj = new Car();
}
}
2. Multilevel Inheritance
class Vehicle {
Vehicle() {
System.out.println("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
System.out.println("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
System.out.println("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
Car obj = new Car(); // Triggers all constructors in order
}
}
class Vehicle {
3. Hierarchical Inheritance Vehicle() {
System.out.println("This is a Vehicle");
}
}

class Car extends Vehicle {


Car() {
System.out.println("This Vehicle is Car");
}
}

class Bus extends Vehicle {


Bus() {
System.out.println("This Vehicle is Bus");
}
}

public class Test {


public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}
4. Multiple Inheritance (Through Interfaces)

Note: that Java does not support multiple inheritances with classes. In
Java, we can achieve multiple inheritances only through Interfaces.
INTERFACE AND INHERITANCE DIFFERENCE

Java interface is a collection of abstract methods.


interface LandVehicle {
default void landInfo() {
System.out.println("This is a LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
System.out.println("This is a WaterVehicle");
}
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
System.out.println("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
obj.waterInfo();
obj.landInfo();
}
}
Super Keyword
Super is a keyword used to access the immediate parent class from subclass.
There are three ways by which the keyword super is used.

super()
1.Accessing Superclass Members
The super keyword allows you to access fields or methods of the parent class when
they are hidden by the subclass.

2. Calling Superclass Methods

You can use super to call a method from the parent class that has been
overridden in the child class.

3. Calling Superclass Constructors

The super() keyword is used to call the constructor of the parent class.
This must be the first statement in the subclass constructor.
1.Accessing Superclass variable
class A
{
void fun()
{
System.out.println("Method: Class A");
}}
class B extends A The super() is used to access the class variable of immediate
{ parent class.
void fun()
{
System.out.println("Method: Class B");
}
void display()
{
super.fun();
}
public static void main(String args[])
{
B obj =new B();
obj.display();
2. Calling Superclass Methods

The super() is used to invoke the class method of immediate


class A parent class.
{
int x=10;
}
class B extends A
{
int x=20;
void display()
{
System.out.println(super.x);
}
public static void main(String args[])
{
B obj =new B();
obj.display();
}
}
3. Calling Superclass Constructors

class A
{
A()
{
System.out.println("Constructor of Class A");
}
class B extends A
{
B()
{
super();
System.out.println("Constructor of Class B");
}
public static void main(String args[])
{
B obj=new B();
}
}
Method Overriding

Method overriding is a mechanism in which a subclass inherits the methods of superclass and sometimes the
subclass modifies the implementation of a method defined in superclass .

The method of superclass which gets modified in subclass has the same name and type signature.
// Example of Overriding in Java 1
class Animal {
// Base class
void move() { System.out.println(
"Animal is moving."); }
void eat() { System.out.println(
"Animal is eating."); }
}
class Dog extends Animal {
@Override void move()
{ // move method from Base class is overriden in this
// method
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}
public class Geeks {
public static void main(String[] args)
{
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking. }}
// Example of Overriding in Java 2
class Parent {
void show() { System.out.println("Parent's show()"); }
}
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}
class Geeks { Output
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();

Parent obj2 = new Child();


obj2.show();
}
}
Method Overriding Example
class A
{ class OverrideDemo
int a=0; {
void fun(int i) public static void main(String args[])
{ {
this.a=i; B obj_B =new B();
} obj_B.fun(10);//function re-defined in derived class
} }
class B extends A }
{ Output
int b; F:\test>javac OverrideDemo.java
void fun(int i) F:\test>java OverrideDemo
{ value of a:15
int c; value of b:20
b=20;
super.fun(i+5);
System.out.println("value of a:"+a);
System.out.println("value of b:"+b);
c=a*b;
System.out.println("The value of c= "+c);
}
}
Polymorphism
Polymorphism is a mechanism which allows to have many forms of the method having the same name.
That means, a method A() may take an instance of an object of one class and may execute its method or the same
method A() may take another instance of an object and may exec
ute the method belonging to another class.
In the following Java program we have taken the superclass A and build a multilevel inheritance.
class A extends Object public class PolymorphismDemo
{ {
public String toString() public static void main(String[] args) {
{ fun(new C()); //invokes the method toString() of class C
return "A"; fun(new B()); //invokes the method toString() of class B
} fun(new A()); //invokes the method toString() of class A
} }
class B extends A public static void fun(Object x) {
{ System.out.println(x.toString());
public String toString() }
{ }
return "B"; Output
} F:\test>javac PolymorphismDemo.java
} F:\test>java PolymorphismDemo
class C extends B C
{ B
public String toString() A
{
{
return "C";
}}
class Base
{
void display()
{
System.out.println("\n Base Method Called");
}
}
class Derived extends Base
{
void display() //overridden method
{
System.out.println("\n Derived Method Called");
}
}
public class RunPolyDemo
{
public static void main(String args[])
{
Base obj=new Derived();//obj is reference to base class //
which is referred by the derived class
obj.display(); //method invocation determined at run time
}
}
Abstract Classes

We have defined this method as abstract because, its definition is overridden in the subclasses B and C,
another function of class A that is fun2() is a normal function.
abstract class A
public class AbstractClsDemo
{
{
abstract void fun1()
public static void main(String[] args)
void fun2()
{
{
B b=new B();
System.out.println("A:Infun2");
C c=new C();
}}
b.fun1(); //invoking the overridden method of class B
class B extends A
b.fun2();
{
c.fun1();//invoking the overridden method of class C
void fun1()
c.fun2();
{
}
System.out.println("B:In fun1");
}
}
Output
}
F:\test>javac AbstractClsDemo.java
class C extends A
F:\test>java AbstractClsDemo
{
B:In fun1
void fun1()
A:In fun2
{
C:In fun1
System.out.println("C:In fun1");
A:In fun2
}
}
The Final with Inheritance Final Variables and Methods

The final keyword can be applied at three places - final int a = 10;

• For declaring variables final void fun()

• For declaring the methods

• For declaring the class

The finalize() method

void finalize()
{
finalization code
}
Interfaces

• The interface can be defined using following syntax

access_modifier interface name_of_interface

return_type method_name1 (parameter1,parameter2,...parametern);

……..

return_type method_name1 (parameter1,parameter2,...parametern);

type static final variable_name= value;

…….

}
Step 1: Write following code and save it as my_interface.java Step 2: Write following code in another file and save it using
InterfaceDemo.java
public interface my_interface Java Program[Interface Demo.java]
class A implements my_interface
{ {
public void my_method(int i)
void my_method(int val); {
System.out.println("\n The value in the class A: "+i);}
} public void another_method() //Defining another method
Do not compile this program. Simply save it. not declared in interface
{
Step 3: Compile the program created in step 2 and get the System.out.println("\nThis is another method in class A");
following output }}
class Interface Demo
F:\test>javac InterfaceDemo.java {
public static void main(String args[])
F:\test>java InterfaceDemo {
my_interface obj=new A();
The value in the class A: 100 //or A obj=new A() is also allowed
A obj1=new A();
This is another method in class A obj.my_method(100);
obj1.another_method();
}}
Packages

Package is a mechanism in which variety of classes and interfaces can be grouped together.

package name_of_package

package My Package;
We can create hierarchy of packages. For instance if you save the required class files in the subfolder MyPkg3 and
the path for this subfolder is C:\MyPkg1\MyPkg2\MyPkg3 then the declaration for the package in your java
program will be -

package MyPkg1.MyPkg2.MyPkg3;
Creating and Accessing Package

Step 1: Create a folder named My_Package.

Step 2: Create one class which contains two methods. We will store this class in a file named A.java. This file will be stored
in a folder My Package. The code for this class will be as follows-

package My Package; //include this package at the beginning


public class A
{
int a;
public void set_val(int n)
{
a=n;
}
public void display()
{
System.out.println("The value of a is: "+a);
}
}
Step 3: Now we will write another java program named PackageDemo.java .This program will use the methods defined in
class A. This source file is also stored in the subdirectory My Package. The java code for this file is -
import My Package.A; //The java class A is referenced here by
import statement
class Package Demo Step 4: Now, open the command prompt and issue the
{ following commands in order to run the package programs
public static void main(String args[]) throws
NoClassDefFoundError D:\>set CLASSPATH .;D:\;
{
A obj=new A(); //creating an object of class A D:\>cd My Package
obj.set_val(10); //Using the object of class A, the methods
present D:\My_Package>javac A.java
obj.display(); //in class A are accessed
} D:\My_Package>javac PackageDemo.java
}
CLASSPATH D:\My_Package>java Package Demo

set CLASSPATH=.;D:\; The value of a is: 10

D:\>cd My Package D:\My_Package>

D:\My_Package\> Now you can execute the required class files


from this location
Importing Package

You might also like