Unit II
INHERITANCE,PACKAGES AND INTERFACES
Overloading Methods
• When two or more methods within the same class that have the same
name, but their parameter declarations are different. The methods are
said to be overloaded, and the process is referred to as method
overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Demonstrate method overloading.
class Overload
{
void test(int a) // Overload test for one integer parameter.
{
System.out.println("a: " + a);
}
void test(int a, int b) // Overload test for two integer parameters.
{
System.out.println("a and b: " + a + " " + b);
}
void test(double x) //// Overload test for one double parameter.
{
System.out.println(“x:“+x);
}
}
class OverloadDemo
{ public static void main(String args[])
{
Overload ob = new Overload();
ob.test(10);
ob.test(10, 20);
ob.test( 100.50);
}}
Object class
• In Java there is a special class named Object.
• If no inheritance is specified for the classes then all those classes are
subclass of the Object class.
• In other words Object is a superclass of all other classes by default.
• Hence public class A{…..} is equal to public class A extends Object{…..}
• There are two commonly used methods in Object class.
• Those are toString() and equals()
• class A extends Object
• {
• }
• class B extends A
• {
• }
• Class objectclassdemo
• {
• public static void main(String ar[])
• {
• A obj=new A();
• System.out.println(“obj”+obj);
• System.out.println(“obj.to String()”+obj.to String());
• }
• }
objects as Parameters
• The object can be passed to a method as an argument.
• Using dot operator the objects value can be accessed. such a method
can be represented as
• Data type name_of _method(object_name)
•{
• //body of method
•}
• public class objdemo
• {
• int height, width;
• objdemo(int h, int w)
• {
• height=h;
• width=w;}
• void area(objdemo ob)
• {
• int result=(height+ob.height)*(width+ob.width);
• System.out.print(“the area is”+result);}}
• Class demo
• {
• public static void main (String ar[]){
• Objdemo obj1=new objdemo(2,3);
• Objdemo obj2=new objdemo(10,20);
• obj1.area(obj2);}}
Returning Objects
How to return an object from a method?
• We can return an object from a method.
• The data type of such method is a class type.
• Example
• public class objretdemo
•{
• int a;
• objretdemo(int val)
•{
• a=val;
•}
• objretdemo fun()
• {
• objretdemo temp=new objretdemo(a+5); //created a new object
• return temp; // returning the object from this method
• }
• }
• class objret
• {
• public static void main (String ar[])
• {
• objretdemo obj2=new objretdemo(20);
• objretdemo obj1;
• obj1=obj2.fun(); // obj1 gets the value from object temp
• System.out.println(“retuned value is=“+obj1.a);
• }}
• Inheritance
• Inheritance can be defined as the procedure or mechanism of acquiring all
the properties and behaviors of one class to another, i.e., acquiring the
properties and behavior of child class from the parent class.
• When one object acquires all the properties and behaviors of another
object, it is known as inheritance.
• The inheritance can be achieved by incorporating the definition of one
class into another using the keyword extends.
• Concept of Super and Sub classes
• The inheritance is a mechanism in which the child class is derived from a
parent class.
• This derivation is using the keyword extends.
• The parent class is called base class or super class and child class is called
derived class or sub class .
• For example
• Class A //parent class
• {
• ……..
• }
• Class B extends A //child class
• {
• ……..
• }
Types of inheritance
• Single
• Multilevel and
• Hierarchical inheritance
• Multiple and Hybrid inheritance is supported through interface only.
Single Inheritance
• In single inheritance there is one parent (base)and one derived
class(child). This is the most common form of inheritance.
Class A Base class
publc class A
{………………………
………………………
}
Class B Derived class public class B extends A
{ ………………………
………………………
}
• class A
• {
• public void dispA()
• {
• System.out.println(“disp() method of class A”);
• }}
• class B extends A //extending the base class A
• {
• public void dispB()
• {
• System.out.println(“disp() method of class B”);
• }}
• Class singleinherit
• {
• public static void main(String ar[])
• {
• B ob=new B();
The class A is called superclass and the class B is called subclass.
• Ob.dispA();
A superclass is also called as parent class or base class.
• Ob.dispB(); Similarly ,the subclass is also called as child class or derived class.
• }}
Multi Level Inheritance
Public class A
Class A {…………………………………..}
Public class B extends A
{…………………………………..}
Public class C extends B
Class B {…………………………………..}
Class C
When a derived class is derived from a base class which itself is a derived class then that type
of inheritance is called multilevel inheritance.
For example-If class A is a base class and class B is another class which is derived from
A, similarly there is another class C being derived from class B then such a derivation
leads to multilevel inheritance.
• class A
• {
• public void dispA()
• { System.out.println(“disp() method of class A”);}}
• class B extends A //extending the base class A
• {
• public void dispB()
• { System.out.println(“disp() method of class B”);}}
• class C extends B //extending the base class B
• {
• public void dispC()
• { System.out.println(“disp() method of class C”);
• }}
• Class multidemo
• {
• public static void main(String ar[])
• {
• C ob=new C();
• Ob.dispA();
• Ob.dispB();
• Ob.dispC();}}
Hierarchical Inheritance
• Public class A
• {…………………………………..}
Class A
• Public class B extends A
{…………………………………..}
Class B Class C • Public class C extends A
{…………………………………..}
• Class Shape
• {
• double dimension;
• Shape()
• {
• dimension=0;
• }
• }
• Class Circle extends Shape
• {double A;
• Circle(double r)
• {
• dimension=r;
• }
• Void area()
• {
• System.out.println(”the radius of the circle:”+dimension);
• A=3.14*dimension*dimension;
• System.out.println(”Area of the circle:”+A);
• }
• Class Square extends Shape
• {double A;
• Square(double s)
• {
• dimension=s;
• }
• Void area()
• {
• System.out.println(”the side of the square:”+dimension);
• A=dimension*dimension;
• System.out.println(”Area of the Square:”+A);
• }}
• Class inheritdemo
• {
• Public static void main(String ar[])
• {
• Circle C=new Circle(5);
• C.area();
• Square S=new Square(10);
• S.area();
• }}
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.
• Usage of super keyword
• 1. super() invokes the constructor of the parent class.
• 2. super.variable_name refers to the variable in the parent class.
• 3. super.method_name refers to the method of the parent class.
1. The super() will invoke the constructor of the parent class
• class A
• {
• A()
• {
• System.out.println("Constructor of class A");
• }
• }
• public class B extends A
• {
• B()
• {
• super();
• System.out.println("Constructor of class B");
• }
• public static void main(String args[])
Output:
• {
Constructor of class A
• B ob = new B(); Constructor of class B
• }}
2.The super.variablename is used to access the class variable of immediate parent class.
• class A
• {
• int x=10;
• }
• Class B extends A
• {
• int x=20;
• void display()
• {
• System.out.println(super.x);
• }
• public static void main(String ar[])
• {
• B Ob=new B();
• Ob.display();
• }
• } Output
10
3.The super is used to invoke the class method of immediate parent class.
• class A
• {
• void fun()
• {
• System.out.println (“Method: class A”);
• }
• }
• Class B extends A
• {
• void fun()
• {
• System.out.println (“Method: class B”);
• }
• void display()
• {
• super.fun();
• }
• public static void main(String ar[])
• {
• B Ob=new B();
• Ob.display(); Output:
• } Method :Class A
• }
Method overriding
• Declaring a method in the subclass which already exists there in the parent
class is known as method overriding.
• When a class is inheriting a method from a superclass of its own, then
there is an option of overriding the method provided it is not declared as
final.
• There are some rules to implement overriding
• In java , a method can only be written in the child class and not in same
class.
• A constructor cannot be overridden.
• Final declared methods cannot be overridden
• Any method that is static cannot be used to override
Example
• Class employ
• {
• void salary()
• {
• System.out.println(“employ’s salary is displayed ”);
• }
• }
• Class professor extends employ
• {
• Void salary()
• {
• System.out.println(“professor’s salary is displayed too”);
• }
• }
• Class emp
• {
• Public static void main(String ar[])
• {
• employ eob=new employ();
• employ pob=new professor();
• eob.salary();
• pob.salary();
• }
• }
ABSTRACT CLASS
• A class that is declared with abstract keyword, is known as abstract class
in java.
• In inheritance hierarchy, the superclass is very general and less specific.
This class does nothing but only specifies the member function that can
be used in hierarchy. Such a class is called abstract class.
• It can have abstract and non-abstract methods (method with body).
• It cannot be instantiated.
• Example program:
• abstract class A
• {
• abstract void fun1(); //abstract method
• void fun2() //non abstract method
• {
• System.out.println(“A:in fun2”);
• }
• }
• class B extends A
• {
• void fun1()
• {
• System.out.println(“B:in fun1”);
• }
• }
• class abstractdemo
•{
• public static void main(String ar[])
•{
• B Ob=new B();
• Ob.fun1();//invoking the overridden method of class B
• Ob.fun2();
•}
Output:
•} B:In fun1
A:In fun2
Points to remember about abstract classes and abstract methods
• An abstract method must be present in an abstract class only. It
should not be present in a non-abstract class.
• In all the non-abstract subclasses extended from an abstract
superclass all the abstract methods must be implemented.
• An un-implemented abstract method in the subclass is not allowed.
• Abstract class cannot be instantiated using the new operator.
• A constructor of an abstract class can be defined and can be invoked
by the subclasses.
Difference between Abstract class and Concrete class
Abstract class Concrete class
• The abstract keyword is used to define • The keyword class is used to define the concrete
the abstract class. class.
• Abstract class have partial or no • The concrete class contains the data members and
implementation at all. member functions defined within it.
• Abstract classes may contain abstract • Concrete classes contain concrete method i.e.with
methods. code and functionality. Concrete class cannot
contain abstract method.
• Abstract classes always act as a parent • Concrete class can be parent or child or neither of
class. the two.
• Concrete class are usually instantiated in order to
access the belonging data members and member
• Abstract class cannot be instantiated. functions.
Final Methods and classes
• Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
• Final variable
• A variable can be declared as final. If a particular variable is declared
as final then it cannot be modified further. The final variable is always
a constant.
• For example
• final int a=10;
The final method.
• When you declare a method as final, then it is called as final method. A final method cannot be overridden.
• When final keyword is applied to the method, the method overriding is avoided. That means the methods those are declared
with the keyword final cannot be overridden.
• class Parent
• {
• public final void disp()
• {
• System.out.println("disp() method of parent class");
• }
• }
• public class Child extends Parent
• {
• public void disp() //cannot override disp()
• {
• System.out.println("disp() method of child class");
• }
• public static void main(String args[])
• {
Output : We will get error as we are overriding
• Child c = new Child();
the disp() method of the Parent class.
• c.disp(); }
• }
Final class
• If we declare particular class as final, no class can be derived from it.
• Example:
• final class Test
• {
• void fun()
• {
• System.out.println(“Hello”);
• }
• }
• Class Test1 extends Test //cannot inherit from final class Test
• {
• final void fun()
• {
• System.out.println(“Hello”);
• }
• }
INTERFACE IN JAVA
• An interface in java is a blueprint of a class.
• It has static constants and abstract methods.
• The interface in java is a mechanism to achieve abstraction and multiple
inheritance.
• Interface is declared by using interface keyword.
• It provides total abstraction; 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.
• Syntax:
• interface <interface name>
•{
• // declare constant fields
• // declare methods that abstract by default.
•}
Example:
• interface printable
• {
• void print();
• }
• class demo implements printable
• {
• public void print()
• {
• System.out.println("Hello");
• }
• public static void main(String args[])
• {
• demo obj = new demo(); Output: Hello
• obj.print();
• }
• }
Variables in interface
• The variables can be assigned with some values within the interface.
• They are implicitly final and static.
• Even if we do not specify the variables as final and static they are
assumed to be final and static.
Multiple inheritance
• Multiple inheritance is a mechanism in which the child class inherits
the properties from more than one parent classes.
A B
• Java does not support multiple inheritance because it creates
ambiguity when the properties from both the parent classes are
inherited in child class or derived class.
• But it is supported in case of interface because there is no ambiguity
as implementation is provided by the implementation class.
• interface A
• {
• void display1()
• }
• interface B
• {
• void display2()
• }
• Class C implements A,B
• {
• public void display1()
• {
• System.out.println(“from interface A”);
• }
• public void display2()
• {
• System.out.println(“from interface B”); Output
• } from interface A
• public static void main(String ar[]) from interface B
• {
• C Ob=new C();
• Ob.display1();
• Ob.display2();
• }
Difference between class and interface
Class Interface
• The class is denoted by a keyword • The interface is denoted by a keyword
class . interface.
• The class contains data members and • The interface may contain data
methods. members and methods but the
• By creating an instance of a class the methods are not defined.
class members can be accessed. • We cannot create an instance of an
• The members of a class can be interface.
constant or final. • The members of interfaces are always
• The class can use various access declared as final.
specifiers like public,private or • The interface makes use of only public
protected. access specifier.
• Extending Interface
• Interface can be extended similar to the classes. That means we can derive subclasses from the
main class using the keyword extends, similarly we can derive the subinterfaces from main
interfaces by using the keyword extends.
• Syntax is
• interface interface_name2 extends interface _name1
• {
• ………………
• }
• For example
interface A
{
int val=10;
}
interface B extends A
{
void print();
}
Inner classes(Nested classes)
• Inner classes are the nested classes. That means these are the classes that
are defined inside the other classes.
• Syntax
• Access_modifier class Outerclass
•{
• //code
• Access_modifier Class innerclass
• {
• //code
• }
•}
Inner class
• The inner class code has free access to all elements of the outer class
object that contains it.
• The outer class can call the private methods of inner class .
• If the outer class and the corresponding inner class both are public
then any other class can create an instance of this inner class.
• There are four types of inner classes.
• Static member class
• Member class
• Local class
• Anonymous class
• To access the inner class,create an object of the outer class , and then create an object of the inner class:
• Class
̥ outerclass
• {
• Int x=10;
• class innerclass
• {
• Int y=5;
• }
• }
• Class main
• {
• Psvm(String ar[])
• {
• outerclass outobj=new outerclass();
• outerclass.innerclass inobj=outobj. new innerclass();
• System.out.println(inobj.y+outobj.x)
• }
• }
• There are four types of inner classes
• Static member classes:
• This inner class is defined as the static member variable of another class.
• static members of the outer class are visible to the static inner class.
• The non _static members of the outer class are not available to inner class
• Member classes:
• This type of inner class is non static member of outer class.
• Local classes:
• This class is defined within a method of outer class.
• The scope of the inner class is restricted within the method.
• The local classes are completely hidden from the outside world.
• Anonymous classes: is a local class without any name.
• //Static inner class
• class
̥ outerclass
• {
• static Int x=10;
• static class innerclass
• {
• Void disp()
• {
• System.out.println(x);
• }
• }
• Class main
• {
• Public static void main(String ar[])
• {
• outerclass outobj=new outerclass();
• outerclass.innerclass inobj=outobj. new innerclass();
• nobj.disp()
• }}
• //Local inner class example
• public class
̥ outerclass
• {
• Int x=10;
• Void display()
• {
• class local
• { void msg()
• {System.out.print(x);}}
• local l=new local();
• l.msg();}
• public static void main(String ar[])
• {
• outerclass outobj=new outerclass();
• outobj.display();
• }}
Package
• A java package is a group of similar types of classes ,interfaces and sub-packages.
• Package in java can be categorized in two forms, built in package and user defined
package
• There are many built in packages such as java, lang, awt , javax, swing, net, io, util, sql
etc.
Defining a Package
• To create a package ,include a package command as the first statement in a java source
file.
• Any classes declared within that file will belong to the specified package.
• Syntax:
• package <name of package >
• package pack;
• Here pack is the name of the package
• This package statement defines the name space in which the classes are stored. if we
omit the package then the default classes are put in the package that has no name.
Creating and accessing package
• Step1:Create a folder named mypack.
• Step 2: Create one class which contains two methods. We will store this in a file
named A.java. This file will be stored in a folder mypack. The code for this class
will be as follows
package mypack;
public class A
{
int a;
public void set(int n)
{
a=n;
}
public void display()
{
System.out.println(”the value of a is” +a);
}
}
• Step3: 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 mypack;
• import mypack.A;
• Class packagedemo
•{
• public static void main(String arg[])
•{
A obj=new A();
obj.set(10);
obj.display();
•}
•}
• The classes defined in the packages of other program can be easily
reused.
• Two classes from two different packages can have the same name. By
using the package name the particular class can be referred.
• All the standard classes in java are stored in named packages.
• The import statement can be written at the beginning of the java
program, using the keyword import.
• There are two ways of accessing the classes stored in the core
package.
• i) import java.util.Date;
• ii) import java.util.*;