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

CH-3 Java_notes

Uploaded by

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

CH-3 Java_notes

Uploaded by

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

Ch-3 Inheritance, Interface and Package Marks: 12

_________________________________________________________________

Content

3.1 Inheritance: Concept of inheritance and types of inheritance


3.2 Single inheritance, multilevel inheritance, Hierarchical inheritance, methods
and constructor overloading and overriding. Dynamic method Dispatch, final
variables, final methods, use of super, abstract method and classes, static
members.

3.3 Interfaces: Define Interface, implementing interface, accessing Interface,


variables and methods, extending interface, interface reference, nested
interface.

3.4 Package: Define package, type of package naming and creating packages,
accessing package, import statement. Static import, adding class and
interface to a package.

Inheritance

 Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another.
 The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
 Super Class: The class whose features are inherited is known as superclass
(or a base class or a parent class).
 Sub 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.
 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. By
doing this, we are reusing the fields and methods of the existing class.

Page 1
extends Keyword
 extends is the keyword used to inherit the properties of a class. Following is
the syntax of extends keyword.
 Syntax
class super_class_name
{
------
------
}
class Sub_class_name extends super_class_name
{
------
------
}

There are various types of inheritance as demonstrated below.

Page 2
Single Inheritance

 When a subclass is derived simply from its parent’s class then this mechanism
is known as single inheritance.
 In this type there is only one child class and one parent class.

Example 1)
class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);

Page 3
}
}

In the given program, when an object to My_Calculation class is created, a copy of


the contents of the superclass is made within it. That is why, using the object of
the subclass you can access the members of a superclass.

The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable to
the subclass.
If you consider the above program, you can instantiate the class as given below. But
using the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

Note − A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.

Example 2)

Page 4
import java.lang.*;
class sphere
{
int r;
float pi;
sphere(int r, float pi) //super class constructor
{
this.r=r;
this.pi=pi;
}
void volume() //method to display volume of sphere
{
float v=(4*pi*r*r)/3;
System.out.println("Volume of Sphere="+v);
}
}
class hemisphere extends sphere //subclass defined
{
int a;
hemisphere(int r, float pi, int a)
{
super(r,pi);
this.a=a;
}
void volume() //method to display volume of hemisphere
{
super.volume();
float v=(a*pi*r*r*r)/3;
System.out.println("Volume of Hemisphere="+v);
}
}
class volume
{
public static void main(String args[]) //main method
{
hemisphere h=new hemisphere(12, 3.14f, 2);

Page 5
h.volume();
}
}
Output:
Volume of Sphere=602.88
Volume of Hemisphere=3617.28
___________________________________________________________________
Example 3:

class person
{
String name;
int age;
void getdata(String n, int a)
{
name=n;
age=a;
}
void putdata()
{
System.out.println("Employee Details: ");
System.out.println("Employee Name: "+name);
System.out.println("Employee Age: "+age);
}
}
class emp extends person
{
String emp_desig;
int emp_sal;

Page 6
void getdata(String n, int a, String e, int s)
{
super.getdata(n,a);
emp_desig=e;
emp_sal=s;
}
void putdata()
{
super.putdata();
System.out.println("Employee's Designation: "+emp_desig);
System.out.println("Employee's Salary; Rs. "+emp_sal);
}
}
class emp1
{
public static void main(String args[])
{
emp e1=new emp();
e1.getdata("vijay",30,"Manager",50000);
e1.putdata();
}
}

Output:
Employee Details:
Employee Name: vijay
Employee Age: 30
Employee's Designation: Manager
Employee's Salary; Rs. 50000

Multilevel Inheritance

 When a class is derived from already derived class then this mechanism is
known as multilevel inheritance.
 The derived class is called as subclass or child class for its parents class and
this parent class work as child class for its just above parent class.

Page 7
 Multilevel inheritance can go up to any level
___________________________________________________________________
1. e.g.

import java.lang.*;
class Square //super class
{
int length;
Square(int x)
{
length=x;
}
void area() //method to calculate area of square
{
int area=length*length;
System.out.println("Area of Square="+area);
}
}
class Rectangle extends Square //inherit class rectanglefrom class square
{
int breadth;
Rectangle(int x, int y)
{
super(x); //calling super class constructor
breadth=y;
}
void rectArea()
{
int area1=length*breadth;
Page 8
System.out.println("Area of Rectangle="+area1);
}
}
class Box extends Rectangle //inherit class Box from class Rectangle
{
int height;
Box(int x, int y, int z) //calling rectangle class constructor
{
super(x,y);
height=z; }
void volume()//method to display volume of box
{
int volume=length*breadth*height;
System.out.println("Volume of Box="+volume);
}
}
class Shape
{
public static void main(String args[]) //main method
{
Box b=new Box(10,20,30);
//creating object of Box class
b.volume();
b.rectArea();
b.area();
}
}
Output:
Volume of Box=6000
Area of Rectangle=200
Area of Square=100
____________________________________________________________

2. e.g.

Page 9
class account
{
String custname;
int accno;
void getdata(String n, int a)
{
custname=n;
accno=a;
}
void putdata()
{
System.out.println("Customers Account Details\n");
System.out.println("Customers Name: "+custname);
System.out.println("Customers Account Number: "+accno);
}
}
class savingacc extends account
{
int minbal;
int savbal;
void getdata(String n, int a, int m, int s)
{
super.getdata(n,a);
minbal=m;
savbal=s;
}

Page 10
void putdata()
{
super.putdata();
System.out.println("Minimum Balance: "+minbal);
System.out.println("Saving Balance: "+savbal);
}
}
class accdetail extends savingacc
{
int deposits;
int withdrawal;
void getdata(String n, int a, int m, int s, int d, int w)
{
super.getdata(n,a,m,s);
deposits=d;
withdrawal=w;
}
void putdata()
{
super.putdata();
System.out.println("Deposit: "+deposits);
System.out.println("Withdrawal Amount: "+withdrawal);
}
}
class acc
{
public static void main(String args[])
{
accdetail a1=new accdetail();
a1.getdata("Vijay",123,500,10000,5000,2500);
a1.putdata();
}
}
Output:
Customers Account Details
Customers Name: Vijay

Page 11
Customers Account Number: 123
Minimum Balance: 500
Saving Balance: 10000
Deposit: 5000
Withdrawal Amount: 2500
___________________________________________________________________

Hierarchical Inheritance

 In hierarchical inheritance one class is extended by many subclasses.


 It is one to many relationships.
 Many programming problems can be tasked into a hierarchy where certain
features of one level are shared by many others below the level.

import java.io.*;
abstract class shape
{
float dim1,dim2;
void getdata()
{
DataInputStream d=new DataInputStream(System.in);
try
{
System.out.println("Enter the value of Dimension1: ");
dim1=Float.parseFloat(d.readLine());
System.out.println("Enter the value of Dimension2: ");
dim2=Float.parseFloat(d.readLine());
}
catch(Exception e)

Page 12
{
System.out.println("General Error"+e);
}
}
void disp()
{
System.out.println("Dimension1= "+dim1);
System.out.println("Dimension2= "+dim2);
}
abstract void area();
}
class rectangle extends shape
{
double area1;
void getd()
{
super.getdata();
}
void area()
{
area1=dim1*dim2;
System.out.println("The Area of Rectangle is: "+area1);
}
}
class triangle extends shape
{
double area1;
void getd()
{
super.getdata();
}
void area()
{
area1=(0.5*dim1*dim2);
System.out.println("The Area of Triangle is: "+area1);
}

Page 13
}
class methodover1
{
public static void main(String args[])
{
rectangle r=new rectangle();
System.out.println("For Rectangle");
r.getd();
r.disp();
r.area();
triangle t=new triangle();
t.getd();
t.disp();
t.area();
}
}

Output:
For Rectangle
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 5.0
Dimension2= 6.0
The Area of Rectangle is: 30.0
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 6.0
Dimension2= 7.0
The Area of Triangle is: 21.0

Example 2)

class A
{
public void methodA()
{

Page 14
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class H_inheritance
{
public static void main(String args[])
{
B objb = new B();
C objc = new C();
D objd = new D();
//All classes can access the method of class A
objb.methodA();
objc.methodA();
objd.methodA();

Page 15
objb.methodB();
objc.methodC();
objd.methodD();
//objc.methodB(); //error
}
}

___________________________________________________________________

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Page 16
Method and Constructor Overloading

 Method Overloading means to define different methods with the same name
but different parameters lists and different definitions.
 It is used when objects are required to perform similar task but using different
input parameters that may vary either in number or type of arguments.
 Overloaded methods may have different return types.
 Method overloading allows user to achieve the compile time polymorphism.
 Suppose, you have to perform the addition of given numbers but there can be
any number of arguments (let’s say either 2 or 3 arguments for simplicity).
 In order to accomplish the task, you can create two methods sum2num(int,
int) and sum3num(int, int, int) for two and three parameters respectively.
However, other programmers, as well as you in the future may get confused as
the behavior of both methods are the same but they differ by name.
 The better way to accomplish this task is by overloading methods. And,
depending upon the argument passed, one of the overloaded methods is
called. This helps to increase the readability of the program.
Syntax:
 int add( int a, int b) // prototype 1
 int add( int a , int b , int c) // prototype 2
 double add( double a, double b) // prototype 3

For e.g. 1
class Sample
{
int addition(int i, int j)
{ return i + j ; }
String addition(String s1, String s2)
{ return s1 + s2; }
double addition(double d1, double d2)
{ return d1 + d2; }
}
class AddOperation
{

Page 17
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));
}
}

For e.g. 2
class Overload
{
void test (int a)
{
System.out.println(“a”+a);
}
void test (int a, int b)
{
System.out.println(“a & b”+a “and” +b);
}
double test(double a)
{
System.out.println(“Double a” +a);
Return a*a;
}
}
class demo
{
public static void main(String args[])
{
Overload obj = new Overload();
double result;
obj.test(10);
obj.test(10, 20);
result= obj.test(5.5);

Page 18
System.out.println(“result is:”+result);
}
}

Example 3 on Method Overloading


class MethodOverloading {
private static void add(int a,int b)

{
System.out.println("Addition of 2 numbers: " + (a+b));
}

private static void add(int a, int b,int c)


{
System.out.println("Addition of 3 numbers: " + (a+b+c));
}

public static void main(String[] args) {


add(1,5);
add(1, 4,6);
}
}

Example:

class MethodOverloading1 {

// this method accepts int


private static void display(int a){
System.out.println("Display Integer data.");
}

Page 19
// this method accepts String object
private static void display(String a){
System.out.println("DisplayString object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}}

Example:
public class OverloadingExample2
{
private int rollNum;
OverloadingExample2() //dc
{
rollNum =100;
}
OverloadingExample2(int rnum)
{
this();
/*this() is used for calling the default
* constructor from parameterized constructor.
* It should always be the first statement
* inside constructor body.
*/
rollNum = rollNum+ rnum;
}
public int getRollNum()
{
return rollNum;
}
public void setRollNum(int rollNum)

Page 20
{
this.rollNum = rollNum;
}
public static void main(String args[])
{
OverloadingExample2 obj = new OverloadingExample2(15);
System.out.println(obj.getRollNum());
}
}

As you can see in the above program that we called the parameterized
constructor during object creation. Since we have this() placed in
parameterized constructor, the default constructor got invoked from it and
initialized the variable rollNum.

Example:
public class OverloadingExample3
{
private int rollNum;
OverloadingExample3()
{
rollNum =100;
}
OverloadingExample3(int rnum)
{

rollNum = rollNum+ rnum;


this();
}
public int getRollNum() {
return rollNum;
}
public void setRollNum(int rollNum) {
Page 21
this.rollNum = rollNum;
}
public static void main(String args[])
{
OverloadingExample3 obj = new OverloadingExample3(12);
System.out.println(obj.getRollNum());
}
}

Super Keyword:
The super keyword in java is a reference variable that is used to refer parent
class objects. The keyword “super” came into the picture with the concept of
Inheritance. It is majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of
ambiguity for the JVM. We can understand it more clearly using this code
snippet:

/* Base class vehicle */


class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}

Page 22
}
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output:
Maximum Speed: 120
In the above example, both base class and subclass have a member
maxSpeed. We could access maxSpeed of base class in subclass using super
keyword.

2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods
then to resolve ambiguity we use super keyword. This code snippet helps to
understand the said usage of super keyword.

/* Base class Person */


class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{

Page 23
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
class Test
{
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}

Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message()
then, the current class message() is invoked but with the use of super
keyword, message() of superclass could also be invoked.

3. Use of super with constructors: 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 upon
the situation. To access the method of parent class when child class has
overridden that method.

Following is the code snippet to explain the above concept:

Page 24
/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}

Output:
Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using
keyword ‘super’ via subclass constructor.

Method Overriding

Page 25
 There may be situation when we want an object to respond to the same
method but have different behavior when that method is called.
 This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the superclass.
 Then, when that method is called, the method defined in the subclass is
invoked and executed instead of the one in the superclass. This is known as
overriding.
 Method overriding is one of the way by which java achieve Run Time
Polymorphism.
 In overriding return types and constructor parameters of method should
match.

For E.g. No.1


class Super
{
int x;
Super (int x)
{ this.x=x; }
void display()
{ System.out.println(“Super x=”‖+x); }
}
Class Sub extends Super
{
int y; Sub( int x, int y)
{
super (x);
this.y=y;
}
void display()
{
System.out.println(“Super x=”‖ +x);
System.out.println(“Sub y=‖” +y);
}
}
class overrideTest

Page 26
{
public static void main(String arg[])
{
Sub s1= new Sub(100,200);
s1.display();
}
}

For e.g. No.2

class A
{
int i;
A(int a, int b)
{
i=a+b;
}
void add()
{
System.out.println(“Sum of a & b is=” +i);
}
}
class B extends A
{
int j;
B(int a, int b, int c)
{
super(a,b);
j=a+b+c;
}
void add()
{
super.add();
System.out.println(“Sum of a, b & c”+j);
}

Page 27
}
class MethodOverride
{
public static void main(String args[])
{
B b=new B(10,20,30);
b.add();
}
}

Dynamic Method Dispatch

 Dynamic method dispatch is the mechanism by which a call to a overridden


method is resolved at runtime rather than at compile time
 When an overridden method is called through a super class reference, java
determines which method to execute based upon the type of the object being
referred at the time the call is made.
 When an overridden method is called by a reference, java determines which
version of that method to execute based on the type of object it refer to. In
simple words the type of object which it referred determines which version of
overridden method will be called.

Example:
import java.lang.*;
class A
{
void show()
{
System.out.println("in show of A");
}
}

class B extends A
{

Page 28
void show()
{
System.out.println("in show of B");
}
}
class C extends B
{
void show()
{
System.out.println("in show of C");
}
}
class DynaMethod
{
public static void main(String args[])
{
A a = new A(); // object of class A
B b = new B(); // object of class B
C c = new C(); // object of class C
A r; // obtain a reference of type A
r = a; //r refer to object of A
r.show(); // call show() of A
r = b; //r refer to object of B
r.show(); // call show() of B
r = c; //r refer to object of C
r.show(); // call show() of C
}
}
Output:
in show of A
in show of B
in show of C

Reference of class A stores the reference of class A, class B and class C


alternatively. Every call to show() method would result in execution of show()
method of that class whose reference is currently stored by a reference of class

Page 29
A.

Method Overloading Method Overriding


It happens within the same It happens between super class
class and subclass
Method signature should not be Method signature should be
same same.
Method can have any return Method return type should be
type same as super class method
Overloading is early binding or Overriding is late binding or
static binding dynamic binding
They have the same name but, They have the same name as a
have different parameter lists, superclass method. They have
and can have different return the same parameter list as a
types. superclass method. They have
the same return type as a
superclass method
It is resolved at compile time It is resolved at runtime.
Inheritance does not blocked Method overriding blocks the
by method overloading. inheritance.
One method can overload Method overriding can be done
unlimited number of times. only once per method in the
sub class.

Final Variable and Final Method

Page 30
 Final variable: the value of a final variable cannot be changed. final variable
behaves like class variables and they do not take any space on individual
objects of the class.

Example of declaring final variable: final int size = 100;


 final method: making a method final ensures that the functionality defined in
this method will never be altered in any way, ie a final method cannot be
overridden.
Syntax:
final void findAverage()
{
//implementation
}
Example of declaring a final method:
class A
{
final void show()
{
System.out.println(“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
}
}

Page 31
In Java, the final keyword is used to denote constants. It can be used with
variables, methods, and classes.
Once any entity (variable, method or class) is declared final, it can be assigned
only once. That is,
 the final variable cannot be reinitialized with another value
 the final method cannot be overridden
 the final class cannot be extended
Java final Variable
In Java, we cannot change the value of a final variable.
class Main {
public static void main(String[] args) {

// create a final variable


final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}
In the above program, we have created a final variable named age. And we
have tried to change the value of the final variable.
When we run the program, we will get a compilation error with the following
message.
cannot assign a value to final variable AGE
AGE = 45;

Java final Method


In Java, the final method cannot be overridden by the child class. For example,
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

Page 32
class Main extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the
program, we will get a compilation error with the following message.
display() in Main cannot override display() in FinalDemo
public final void display()
{
overridden method is final
}

Java final Class


In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}

// try to extend the final class


class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

Page 33
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final class named FinalClass. Here,
we have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following
message.
cannot inherit from final FinalClass
class Main extends FinalClass { }

Abstract Class

A class that is declared with abstract keyword is known as abstract class in


java. It can have abstract and non-abstract methods (method with body).
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Another way, it shows only important things to the
user and hides the internal details.
A method must be always redefined in a subclass of an abstract class, as
abstract class does not contain method body. Thus abstract makes overriding
compulsory.
Class containing abstract method must be declared as abstract.
You cannot declare abstract constructor, and so, objects of abstract class
cannot be instantiated.
Syntax :
abstract class < classname>
{
abstract method1(…);
method2(….);
}

Example:1

Page 34
abstract class A
{
abstract void disp();
void show()
{
System.out.println(“show method is not abstract”);
}}
class B extends A
{
void disp()
{
System.out.println(“inside class B”);
}
}
class test
{
public static void main(String args[])
{
B b = new B();
b.disp();
b.show();
}
}
Output :
show method is not abstract
inside class B

Example: 2

Page 35
abstract class Employee
{
int empid;
String empname;
Employee(int e,String n)
{
empid=e;
empname=n;
}
void display()
{
System.out.println("Employee ID is: "+empid);
System.out.println("Employee name is: "+empname);
}
}
class Manager extends Employee
{
int mid;
String mname;
int phno;
Manager(int e,String n,int m,String mn,int p)
{
super(e,n);
mid=m;
mname=mn;
phno=p;

Page 36
}
void displaym()
{
super.display();
System.out.println("Manager ID is: "+mid);
System.out.println("Manager name is: "+mname);
System.out.println("Phone no is: "+phno);
}
}
class Worker extends Employee
{
int wid;
String wname;
double whours;
Worker(int e,String n,int w,String wn,double wh)
{
super(e,n);
wid=w;
wname=wn;
whours=wh;
}
void displayw()
{
super.display();
System.out.println("worker ID is: "+wid);
System.out.println("worker name is: "+wname);
System.out.println("Working hours= "+whours);
}
}
class Company
{
public static void main(String arg[])
{
Manager m1=new Manager(11,"Neel",121,"Sameer",123456);
m1.displaym();

Page 37
Worker w1=new Worker(22,"Ishan",222,"Priyank",6);
w1.displayw();
}
}

Example: 3

import java.io.*;
abstract class shape
{
float dim1,dim2;
void getdata ()throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter dimension 1");
dim1 =Float.parseFloat(br.readLine());
System.out.println("Enter dimension 2");
dim2=Float.parseFloat(br.readLine());
}
void disp()
{
System.out.println("dimension 1="+dim1);
System.out.println("dimension="+dim2);
}
abstract void area();
}
class Rectangle extends shape

Page 38
{
double area1;
float dim1,dim2;
void getd() throws IOException
{
super.getdata();
}
void area()
{
area1=dim1*dim2;
System.out.println("area of rectangle is"+area1);
}
}
class triangle extends shape
{
double area;
float dim1,dim2;
void getd1() throws IOException
{
super.getdata();
}
void area()
{
area=(0.5*dim1*dim2);
System.out.println("area of triangle is"+area );
}
}
class abs
{
public static void main(String args[]) throws IOException
{
Rectangle r =new Rectangle();
System.out.println("for Rectangle:");
r.getd();
r.disp();

Page 39
r.area();
System.out.println("for triangle:");
triangle t =new triangle ();
t.getd1();
t.disp();
t.area();
}
}

The abstract keyword is used to achieve abstraction in Java. It is a non-access


modifier which is used to create abstract class and method.
The role of an abstract class is to contain abstract methods. However, it may also
contain non-abstract methods. The method which is declared with abstract keyword
and doesn't have any implementation is known as an abstract method.

Syntax:-
abstract class Employee
{
abstract void work();
}

Rules of abstract keyword


Don'ts
o An abstract keyword cannot be used with variables and constructors.

o If a class is abstract, it cannot be instantiated.

o If a method is abstract, it doesn't contain the body.

o We cannot use the abstract keyword with the final.

o We cannot declare abstract methods as private.

o We cannot declare abstract methods as static.

o An abstract method can't be synchronized.


Do's
o An abstract keyword can only be used with class and method.

o An abstract class can contain constructors and static methods.

o If a class extends the abstract class, it must also implement at least one of the
abstract method.

o An abstract class can contain the main method and the final method.

o An abstract class can contain overloaded abstract methods.


Page 40
o We can declare the local inner class as abstract.

o We can declare the abstract method with a throw clause.


Example: //Abstract class containing the abstract method
abstract class Vehicle
{
abstract void bike();

}
class Honda extends Vehicle
{
void bike() //override
{
System.out.println("Bike is running");

}
}
public class AbstractExample1
{
public static void main(String[] args) {
Honda obj=new Honda();
obj.bike();
}
}

Example:
//Abstract class containing the abstract and non-abstract method
abstract class Vehicle
{
abstract void bike();
void car()
{
System.out.println("Car is running");
}
Page 41
}
class Honda extends Vehicle
{
//Override
void bike() {
System.out.println("Bike is running");
}
}

public class AbstractExample2


{
public static void main(String[] args) {
Honda obj=new Honda();
obj.bike();
obj.car();
}

Example:
//Abstract class containing the constructor
abstract class Vehicle
{
String msg;

Vehicle(String msg)
{
this.msg=msg;
}

void display()
{
System.out.println(msg);
}

Page 42
}
class Honda extends Vehicle
{

Honda(String msg)
{
super(msg);
//super.display();

public class AbstractExample3


{

public static void main(String[] args) {


Honda obj=new Honda("Constructor is invoked");
obj.display();

}
}

Example:
//Abstract class containing overloaded abstract methods
abstract class Vehicle
{

abstract void display(); //zero parameter


abstract void display(String msg); // single pparameter

}
class Honda extends Vehicle
{

Page 43
//override zero parameter
void display()
{

System.out.println("abstract method is invoked");


}

//override single pparameter


void display(String msg)
{

System.out.println(msg);
}

}
public class AbstractExample4 {

public static void main(String[] args) {


Honda obj=new Honda();
obj.display();
obj.display("overloaded abstract method is invoked");
}
}

Example:
//Inner abstract class
class Vehicle
{
abstract class Car
{
abstract void display();
}

class Honda extends Car


{
//Override

Page 44
void display()
{
System.out.println("inner abstract class is invoked");
}
}
}
public class AbstractExample5 {
public static void main(String[] args) {
Vehicle obj=new Vehicle();
Vehicle.Car c=obj.new Honda();
c.display();
}
}
Static Members

 When a number of objects are created from the same class, each instance has
its own copy of class variables. But this is not the case when it is declared as
static.
 Static method or a variable is not attached to a particular object, but rather to
the class as a whole. They are allocated when the class is loaded.
 If some objects have some variables which are common, then these variables
or methods must be declared static.
 To create a static variable, precede its declaration with keyword static. Static
variables
c c n n hhhn need not be called on any object.
Example:
int a; // normal variable
static int a; //static variable
class s
{
int a,b;
static int c;
}
class statictest
{
public static void main(String args[])

Page 45
{
s ob1=new s();
s ob2=new s();
s ob3=new s();
}
}
In above program variable a and b are declared as int variable whereas the variable
c is declared as static variable. Static variable will be common between all the
objects.

When we accessing variable as ‘a’ we cannot access it directly without the reference
of the object because ‘a’ exist in all three objects. So to access the value of ‘a’ we
must link it with the name of the object. But the ‘c’ is static variable and it is
common between all the objects so we can access it directly. But when we are
accessing it outside the class in which it is declared, we must link it with the name of
the class i.e. with S as S.c=20;

Sr.No. Static Final


1. Static keyword can be applied to Final keyword can be applied to
instance variables and methods all constructors that is variable,
but not to the classes. methods and classes.
2. Static variable can be Final variable can be reinitialized.
reinitialized.
3. Static variable is global variable Final variable is a constant
shared by all the instances of variable and it cannot be
object and it has only single changed.
copy.
4. Static variable can change their Final variables cannot be changed
value. because they are constants.

static is a non-access modifier in Java which is applicable for the following:


Page 46
1. blocks
2. variables
3. methods
4. nested classes

To create a static member(block, variable, method, nested class), precede its


declaration with the keyword static. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any
object. For example, in below java program, we are accessing static
method m1() without creating any object of Test class.

// Java program to demonstrate that a static member


// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

Output:
from m1

Static blocks
If you need to do computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating use of static blocks.

// Java program to demonstrate use of static blocks


class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;

Page 47
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}

Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40

Static variables
When a variable is declared as static, then a single copy of variable is created and
shared among all objects at class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables: -
 We can create static variables at class-level only.
 static block and static variables are executed in order they are present in a
program.
Below is the java program to demonstrate that static block and static variables are
executed in order they are present in a program.

// java program to demonstrate execution


// of static blocks and variables
class Test
{
// static variable
static int a = m1();

// static block
static {
System.out.println("Inside static block");
}

// static method
static int m1() {
System.out.println("from m1");
return 20;
}

// static method(main !!)

Page 48
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}

Output:
from m1
Inside static block
Value of a : 20
from main

Static methods
When a method is declared with static keyword, it is known as static method. The
most common example of a static method is 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. Methods declared as static have several restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Below is the java program to demonstrate restrictions on static methods.

// java program to demonstrate restriction on static methods


class Test
{
// static variable
static int a = 10;

// instance variable
int b = 20;

// static method
static void m1()
{
a = 20;
System.out.println("from m1");

// Cannot make a static reference to the non-static field b


b = 10; // compilation error

// Cannot make a static reference to the


// non-static method m2() from the type Test
m2(); // compilation error

Page 49
// Cannot use super in a static context
System.out.println(super.a); // compiler error
}

// instance method
void m2()
{
System.out.println("from m2");
}

public static void main(String[] args)


{
// main method
}
}

When to use static variables and methods?


Use the static variable for the property that is common to all objects. For example, in
class Student, all students share the same college name. Use static methods for
changing static variables.
Consider the following java program, that illustrate the use of static keyword with
variables and methods.

Why is the Java main method static?


Ans) It is because the object is not required to call a static method. If it were a non-
static method, JVM creates an object first then call main() method that will lead the
problem of extra memory allocation.

3.2 Interfaces

 An interface is collection of abstract method and it is defined much like class.


 Writing an interface is similar to the class, with abstract methods and final
field. This means that interface do not specify any code to implement those
methods & data fields containing only constants.
 Interfaces cannot be instantiated they can be only implemented by the classes
or extended by other Interfaces.
 Interfaces are design to support dynamic method resolution at run time.

Page 50
 The general from of interface is
access interface interface_name
{
variable declaration;
method declaration;
}
 Access is either public or not used when no access specifier is included, then
default access result and interface is only available to other member of the
package in which it is declared.
 For e.g.-
public interface IF4IA
{
String Lecture=”JPR”;
int benches=35;
void display();
}

Implementing Interface

 A class can only inherit from one super class. However, a class may implement
several interfaces.
 To declare a class that implements an interface, you need to include
‘implements’ clause in the class declaration.
 Your class can implements keyword is followed by a ‘comma separated list’ of
the interface implemented by a class.
Syntax:- class class_name implements interface
{
//body
}
OR
class class_name extends class_name implemnts interface 1,2

For e.g.-
inteface shape
{
public String baseclass="Shape";

Page 51
public void draw();
}
class circle implements shape
{
public void draw()
{
System.out.println("Circle drawn here");
}
}

Accessing Interface Variables and Method

 An interface can use to declare set of constants that can be used in different
classes. This is similar to creating header files in c++ to contain a large no. of
constants.
 Such interface does not contain methods, there is no need to worry about
implementing methods.
 All variable declared in interface must be constant.
For e.g._
interface one
{
int x=12;
}
interface two
{
int y=10;
void display();
}
class demo implemets one, two
{
int a=x;
int b=y;
public viod display()
{
System.out.println("x in interfece one" +x);

Page 52
System.out.println("y in interfece one" +y);
System.out.println("x & y"+(x+y));
}
public void disp()
{
System.out.println("Value access from interface one:" +a);
System.out.println("Value access from interface two:" +b);
}
}
class multipleinterface
{
public static void main(String args[])
{
demo d= new demo();
d.display();
d.disp();
}
}

Extending Interface

 An interface can extend another interface, similarly to the way that a class can
extend another class.
 The extends keywords is used to extend an interface, and the child interface
inheritas the methods of the parent interface.
 Syntax: -
interface class2 extends class1
{
//body
}
For e.g.:-
inteface A
{
void show();
}
interface B extends A

Page 53
{
void display();
}
class C implements B
public void show()
{
System.out.println("calling interface A");
}
public void display()
{
System.out.println("calling interface B");
}
public void disp()
{
System.out.println("class C is working");
}
}
class D
{
Public static void main(String a[])
{
C object=new C();
object.show();
object.display();
object.disp();
}}
How to achieve multiple inheritance?

 It is type of interface where a derived class may have more than one parent
class.
 It is not possible in case of Java as you cannot have two parent classes at the
parent level, instead there can be one class and one interface at parent level
to achieve multiple inheritance.
 Interface is similar to classes but can contain final variable and abstract
methods. Interfaces can be implemented to a derived class.
 For e.g : -

Page 54
interface sports
{
int sport_wt=5;
public void disp();
}
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
result (int r, String nm, int m11,int m12)
super (r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
{
result r= new result(101,"abc",75,75);

Page 55
r.disp();
}
}
___________________________________________________________________
Example No. 2

interface Gross
{
double TA=800.0;
double DA=3500;
void gross_sal();
}
class Employee
{
String name;
double basic_sal;
Employee(String n, double b)
{
name=n;
basic_sal=b;
}
void display()
{
System.out.println("Name of Employee :"+name);
System.out.println("Basic Salary of Employee :"+basic_sal);
}
}
class Salary extends Employee implements Gross
{
double HRA;

Page 56
Salary(String n, double b, double h)
{
super(n,b);
HRA=h;
}
void disp_sal()
{
Super.display();
System.out.println("HRA of Employee :"+hra);
}
public void gross_sal()
{
double gross_sal=basic_sal + TA + DA + HRA;
System.out.println("Gross salary of Employee :"+gross_sal);
}
}
class EmpDetails
{
public static void main(String args[])
{
Salary s=new Salary("Sachin",8000,3000);
s.disp_sal();
s.gross_sal();
}
}

Nested Interface
 An interface which is declared within another interface or class is known as
nested interface.
 The nested interface is used to group related interfaces so that they can be
easy to maintain.
 The nested interface must be referred by the outer interface or class.
 A nested interface can be declared as public, private or protected.
 Syntax: -
1. Nested interface declared within interface
interface interface_name

Page 57
{
inetrface nested_interface_name
{
-------
-------
}
}

For E.g.
interface display
{
void show();
interface message
{
void msg();
}
}
class test implemets display.message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String a[])
{
display.message message= new test();
message.msg();
}
}
___________________________________________________________________
2. Interface within class
interface class_name
{
inetrface nested_interface_name
{
-------

Page 58
-------
}
}

For E.g

class Test
{
interface Yes //nested interface
{
void show();
}
}

class Testing implements Test.Yes


{
public void show()
{
System.out.println("show method of interface");
}
}

class A_nested_interface
{
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj=t;//reference
obj.show();
}
}

Example 2:
// Java program to demonstrate working of

Page 59
// interface inside another interface.

interface Test
{
interface Yes
{ int a=20;
public void show();
}
}

class Testing implements Test.Yes


{
public void show()
{System.out.println("a="+a);
System.out.println("shows method of interface");
}
}

class A_nested_inteface_1
{
public static void main(String[] args)
{
Test.Yes obj; //creating varible on interface
Testing t = new Testing();
obj = t;
obj.show();
}
}

Class interface
Classes are not used to implement The interfaces are used in java to
multiple inheritance. implementing the concept of multiple
inheritance.
The member of a class can be constant The members of an interface are
or variables. always declared as constant i.e. their

Page 60
values are final.
The class definition can contain the The methods in an interface are
code for each of its methods. That is abstract in nature. I.e. there is no code
the methods can be abstract or non- associated with them. It is defined by
abstract. the class that implements the
interface.
Class contains executable code. Interface contains no executable code.
Memory is allocated for the classes. We are not allocating the memory for
the interfaces.
We can create object of class. We can ‘t creates object of interface.
Classes can be instantiated by Interface cannot be used to declare
declaring objects. objects. It can only be inherited by a
class.
Classes can use various access Interface can only use the public
specifiers like public, private or access specifier.
protected.
Class contains constructors. An interface does not contain any
constructor.
Classes are always extended. Interfaces are always implemented.
A class can extend only one class (no Interfaces can extend one or more
multiple inheritance), but it can other interfaces. Interfaces cannot
implement many interfaces. extend a class, or implement a class or
interface.
An abstract class is fast. An interface requires more time to find
the actual method in the
corresponding classes.

Package

 Package is nothing more than the way we organize files into different
directories according to their functionality, usability as well as category they
should belongs to.
 Packaging also helps us to avoid class name collision when we use the same
class name as that of others.
 Packages act as containers for classes.
Page 61
 Syntax: -
package pakage_name;
For e.g.
package A;
class ABC
{
------
------
}
Types of packages: -
1. Java API Package

java.lang: language support classes. These are classes that java


compiler itself uses and therefore they are automatically
imported. They include classes for primitive types, strings,
math functions, threads and exceptions.
java.util language utility classes such as vectors, hash tables, random
numbers, date etc.
java.io: input/output support classes. They provide facilities for the
input and output of data
java.awt set of classes for implementing graphical user interface. They
include classes for windows, buttons, lists, menus and so on.
java.net classes for networking. They include classes for
communicating with local computers as well as with internet
servers
java.applet classes for creating and implementing applets.

Classes stored in package can be accessed in two ways


 import java.awt.font;
 import java.awt.*;

Naming Convention:
 Package names are written in all lower case to avoid conflict with the names of
classes or interfaces.
 All class name begins with an uppercase letter and method name begin with
lowercase letters

Page 62
 For e.g. :- double x=java lang.Math.sqrt(x); where lang is package name and
Math is class name

Creating Package:
 Declare a package at beginning of a file using syntax: - package
package_name;
 Define the class that is to be put inside the package and declare it as public.
 Create subdirectory under the directory where the main source files are
stored.
 Store the listing as classname.java files in the subdirectory created.
 Compile the file, this creates .class file in the subdirectory.

Accessing Package:
 Package can be accessed using keyword import.
 There are 2 ways to access java system packages:
o Package can be imported using import keyword and the wild card(*) but
drawback of this shortcut approach is that it is difficult to determine
from which package a particular member name.
Syntax: import package_name.*;
For e.g. import java.lang.*;
o The package can be accessed by using dot(.) operator and can be
terminated using semicolon(;)
Syntax: import package1.package2.classname;
For e.g. VP.IF.IF4I.IF4IA

Example 1: Develop a program named myInstitute include class name as


department with one method to display the staff of that department.
Develop a program to import this package in java application and call the
method define in the package.
package myInstitute;
public class department
{
public void display()
{
System.out.println("leon");

Page 63
System.out.println("shreyas");
}
(main code)
import myInstitute.*;
public class demo
{
public static void main(String a[])
{
department d=new department();
d.display();
}
}

Example 2:
Develop a program which consist of the package named let_me_calculate
with a class named calculator and a method name add to add two integer
no. import let_me_calculate package in anather program to add two no.
package let_me_calculate;
public class calculate
{
public void add()
{
int a=20;
int b=30;
int c=a+b;
System.out.println("addition="+c);
}
}
import let_me_calculate.*;
public class calculator
{
public static void main(String arg[])
{
calculate c=new calculate();

Page 64
c.add();
}
}

‘Import’ Statement: -

i) The import keyword is used to import built-in packages & user defined packages.
So that your class can refer a class that is in another package by directly using its
name.
ii) There are different ways to refer to a class that is present in different packages:-

1. Import only the class you want to use


For eg:-
Import java.util.Date;
Class MyDate extends Date
{
//Body of Class
}
2.) Import all the classes from particular package.
For eg:-
import java.util.*;
Class MyDate extends Date
{
//Body of Class
}
Static Import:-

i) Static import is a feature that expands capabilities of import keywords. It is used to


import Static member of a class.
ii) Using static import, it is impossible to refer to static member directly without its
class name.
iii) There are 2 general forms of Static import statement

1. Import only a single static member of a class:-


Syntax:

Page 65
import static package.classname static membername;
For eg:-
import static java.lang.Math.sqrt;
2. Import all static members a class.
Syntax:
Import static package.classname.*;
For Eg:-
Adding class to a package

Structure:-
Package p1
public class A
{
/body of class
}
Create a file outside of package which consists of main method
import p1.*;
Class B
{
public static void main (String args[])
{
// create object of class which is in package
}
}
Example: //without using static import

class Geeks
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(4));
System.out.println(Math.pow(2, 2));
System.out.println(Math.abs(6.3));
}
}

Page 66
Example: // using static import

import static java.lang.Math.*;


class Geeks {
public static void main(String[] args)
{
System.out.println(sqrt(4));
System.out.println(pow(2, 2));
System.out.println(abs(6.3));
}
}

Page 67

You might also like