UNIT II
Class:
A class is the blueprint from which individual objects are created.
This means the properties and actions of the objects are written in the class.
Class Declaration Syntax:
class ClassName
{
VariableDeclaration-1;
VariableDeclaration-2;
VariableDeclaration-3;
VariableDeclaration-n;
returnType methodname-1([parameters list])
{
body of the method…
}
returnType methodname-2([parameters list])
{
body of the method…
}
returnType methodname-3([parameters list])
{
body of the method…
}
}// end of class
Object:
Object is an entity of a class.
1
Object Creation Syntax:
ClassName objectName=new className ();
Class Members:
All the variable declared and method defined inside a class are called class members.
Instance variables: The variables defined within a class are called instance Variables (data
members).
Methods: The block in which code is written is called method (member functions).
The Java programming language defines the following kinds of variables:
There are 4 types of java variables
instance variables
class variables
local variables
Parameters
Instance variables:
Instance variables are declared inside a class. Instance variables are created when the
objects are instantiated (created). They take different values for each object.
Class variables:
Class variables are also declared inside a class. These are global to a class. So these
are accessed by all the objects of the same class. Only one memory location is created for a
class variable.
Local variables:
Variables which are declared and used with in a method are called local variables.
Parameters:
Variables that are declared in the method parenthesis are called parameters.
Class and Object Example:
class Test
{ int a; //default access
void setData(int i)
{
a=i;
}
int dispData()
{
2
return a;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test(); //object creation
[Link](100);
[Link](" value of a is:-”+[Link]());
}
}
Access specifiers (Or) Access Control (Or) access Modifiers or Access Control for Class
Members (Or) Accessing Private Members of Class:
An access specifier determines which feature of a class (class itself, data members,
methods) may be used by another classes.
Java supports four access specifiers:
1. The public access specifier
2. The private access specifier
3. The protected access specifier
4. The Default access specifier
Public:
If the members of a class are declared as public then the members (variables/methods) are
accessed by out side of the class.
Private:
If the members of a class are declared as private then only the methods of same class can
access private members (variables/methods).
Protected:
Discussed later at the time of inheritance.
Default access:
If the access specifier is not specified, then the scope is friendly. A class, variable, or method
that has friendly access is accessible to all the classes of a package (A package is collection
of classes).
Example:
class Test
{
int a; //default access
public int b; // public access
private int c; // private access
//methods to access c
3
void setData(int i)
{
c=i;
}
int dispData()
{
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test();
//a and b can be accessed directly
ob.a=10;
ob.b=20;
// c can not be accessed directly because it is private
//ob.c=100; // error
// private data must be accessed with methods of the same class
[Link](100);
[Link](" value of a, b and c are:"+ob.a+" "+ob.b+"
"+[Link]());
[Link]();
}
}
Assigning One Object to Another or Cloning of objects:
We can copy the values of one object to another using many ways like :
1. Using clone() method of an object class.
2. Using constructor.
3. By assigning the values of one object to another.
4. in this example, we copy the values of object to another by assigning the values of
one object to another.
Example:
class Copy
{
int a=10;
}
class CopyObject
{
public static void main(String args[])
{
Copy c1=new Copy();
Copy c2=c1;
[Link]("object c1 value-"+c1.a);
[Link]("object c2 value-"+c2.a);
}
4
}
Constructors:
1. JAVA provides a special method called constructor which enables an object to
initialize itself when it is created.
2. Constructor name and class name should be same.
3. Constructor is called automatically when the object is created.
4. Person p1=new Person() invokes the constructor Person() and Initializes the
Person object p1.
5. Constructor does not return any return type (not even void).
There are two types of constructors.
Default constructor: A constructor which does not accept any parameters.
Parameterized constructor:A constructor that accepts arguments is called parameterized
constructor.
Default constructor Example:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle() // Default Constructor method
{
[Link]("Constructing Rectangle..");
length=10;
bredth=20;
}
int rectArea()
{
return(length*bredth);
}
}
class Rect_Defa
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
[Link]("Area of rectangle="+[Link]());
}
}
Note: If the default constructor is not explicitly defined, then system default constructor
automatically initializes all instance variables to zero.
Parameterized constructor:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle(int x,int y) // Constructor method
{
length=x;
bredth=y;
}
int rectArea()
{
return(length*bredth);
5
}
}
class Rect_Para
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(5,10);
[Link]("Area of rectangle="+[Link]());
}
}
Overloaded Constructor Methods:
Writing more than one constructor with in a same class with different parameters is
called constructor overloading.
Example:
class Addition
{
int a,b;
Addition()
{
a=10;
b=20;
}
Addition(int a1,int b1)
{
a=a1;
b=b1;
}
void add()
{
[Link]("Addition of "+a+" and "+b+" is "+(a+b));
}
}
class ConsoverLoading
{
6
public static void main(String args[])
{
Addition obj=new Addition();
[Link](); //output:30
Addition obj2=new Addition(2,3);
[Link](); // output: 5
}
}
Nested Classes: nested class is a class that is declared inside the class or interface. it can
access all the members of the outer class, including private data members and methods.
Advantages:
1. Nested classes can access all the members (data members and methods) of the outer
class, including private.
2. to develop more readable and maintainable code
3. Code Optimization
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.
o Non-static nested class (inner class)
1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class
Example: local inner class
public class localInner1
{
private int data=30;//instance variable
void display()
{
class Local
{
void msg()
7
{
[Link](data);
}
}
Local l=new Local();
[Link]();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
[Link]();
}
}
Example: member inner class
class Outer
{
int a=10;
class Inner // member inner class
{
int b=20;
}
}
class MemberInnerClass
{
public static void main(String args[])
{
Outer m=new Outer();
[Link] n=[Link] Inner();//syntax to create inner class object
[Link](m.a+n.b);
}
}
Example: member inner class
class Outer
{
static int a=10;
static void sample()
{
[Link]("Hello I am method of outer class");
}
static class Inner//static Inner Class
{
int b=20;//instance variable
void display()
8
{
sample();
[Link]("I am outer class varible:"+a);
}
}
}
class StaticInnerClass
{
public static void main(String args[])
{
[Link] m=new [Link]();
[Link]("I am Inner class varible:"+m.b);
[Link]();
}
}
Final Class and Methods:
Final Class: Classes declared as final cannot be inherited.
Syntax:
final class A
{
}
class B extends A // cannot be inherited
{ ---
}
Example: (Error Will get while executing following program)
final class A
{
int a=10;
}
class B extends A //can't inherit because class-A is defined as final class
{
int b=20;
}
class Final_Class
{
public static void main(String args[])
{
B obj=new B();
[Link](obj.a+obj.b);
}
}
9
Final Method:
To prevent method riding final keyword is used.
Methods declared as final cannot be overridden.
Example: (Attempt to override final methods leads to compile time error.)
class A
{
int a=10;
final void display()
{
[Link]("I am display() of class-A");
[Link]("my value is:"+a);
}
}
class B extends A
{
int b=20;
void display() //can’t be overriden
{
[Link]("I am display() of class-B");
[Link]("my value is:"+b);
}
}
class Final_Methods_Classes
{
public static void main(String args[])
{
B b=new B();
[Link]();
}
}
Passing Arguments by Value and by Reference
There is only call by value in java, not call by reference but we can pass non-primitive
datatype to function to see the changes done by callee function in caller function.
If we call a method passing a value, it is known as call by value. The changes being
done in the called method, is not affected in the calling method.
Example 1: Passing Primitive datatype to function
class Example
{
int a=10;
void change(int a) //called or callee function
{
a=a+100;
}
}
class CallByValue
10
{
public static void main(String args[]) //calling function
{
Example e=new Example();
[Link]("a value before calling change() :"+e.a); //10
[Link](10); //call by value(passing primitive data type)
[Link]("a value after calling change() :"+e.a); //10
}
}
Example 1: Passing Primitive datatype to function
(Or)
Class Objects as Parameters in Methods:
class Example
{
int a=10;
void change(Example x) //called or callee function
{
x.a=x.a+100;
}
}
class CallByValue
{
public static void main(String args[]) //calling function
{
Example e=new Example();
[Link]("a value before calling change() :"+e.a); //10
[Link](e); //call by value(passing non primitive data type) (or) Class
Objects as Parameters in Methods
[Link]("a value after calling change() :"+e.a); //110
}
}
‘this’ keyword:
‘this’ is a keyword that referes to the object of the class where it is used.
When an object is created to a class, a default reference is also created internally to
the object.
11
class Sample
{
private int x;
Sample()
{
this(10); // calls parameterized constructor and sends 10
[Link](); //calls present class method
}
Sample(int x)
{
this.x=x; // referes present class reference variable
}
void access()
{
[Link]("X ="+x);
}
}
class ThisDemo
{
public static void main(String[] args)
{
Sample s=new Sample();
}
}
Methods in java:
Method in Java is a collection of instructions that performs a specific task. It provides
the reusability of code.
Syntax of Defining a Method in java:
12
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined method:
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library method or
built-in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the [Link] class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Example:
public class Demo
public static void main(String[] args)
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
User-defined Method:
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
Example:
import [Link];
13
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
}
}
Overloaded Methods or Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Example:
class Method
{
int add(int a,int b)
{
[Link]("I am Integer method");
return a+b;
}
float add(float a,float b,float c)
{
[Link]("I am float method");
return a+b+c;
}
int add(int a,int b,int c)
{
[Link]("I am Integer method");
return a+b+c;
}
14
float add(float a,float b)
{
[Link]("I am float method");
return a+b;
}
}
class MethodOverLoad
{
public static void main(String args[])
{
Method m=new Method();
[Link]([Link](10,20));
[Link]([Link](10.2f,20.4f,30.5f));
[Link]([Link](10,20,30));
[Link]([Link](10.2f,20.4f));
}
}
Recursive Methods:
A method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
Example:
public class Recursion
{
static int count=0;
static void p()
{
count++;
if(count<=5)
{
[Link]("hello "+count);
p();
}
}
public static void main(String[] args)
{
p();
}
}
15
Nesting of Methods:
A method can be called by using only its name by another method of the same class that is
called Nesting of Methods.
Syntax:
class Main
{
method1()
{
// statements
}
method2()
{
// statements
// calling method1() from method2()
method1();
}
method3()
{
// statements
// calling of method2() from method3()
method2();
}
}
Example:
public class NestingMethod
{
public void a1()
{
[Link]("****** Inside a1 method ******");
// calling method a2() from a1() with parameters a
a2();
}
public void a2()
{
[Link]("****** Inside a2 method ******");
}
public void a3()
{
[Link]("****** Inside a1 method ******");
a1();
}
public static void main(String[] args)
{
// creating the object of class
16
NestingMethod n=new NestingMethod();
// calling method a3() from main() method n.a3(a, b);
}
}
Overriding Method: If subclass has the same method as declared in the parent class, it is known as
method overriding.
Uses: runtime polymorphism
Rules:
There must be a IS-A relationship(inheritance).
The method must have same method signature as in the parent class.
Example:
class SuperClass
{
void calculate(double x)
{
[Link]("Square value of X is: "+(x*x));
}
}
class SubClass extends SuperClass
{
void calculate(double x)
{
super();
[Link]("Square root of X is: "+[Link](x));
}
}
class MethodOver
{
public static void main(String args[])
{
SubClass s=new SubClass();
[Link](2.5);
}
}
Note: when a super class method is overridden by the sub class method calls only the sub class
method and never calls the super class method. We can say that sub class method is replacing super
class method.
17
Inheritance
Inheritance is the technique which allows us to inherit the data members and methods from base class to
derived class.
• Base class is one which always gives its features to derived classes.
• Derived class is one which always takes features from base class.
A Derived class is one which contains some of features of its own plus some of the data
members from base class.
Process of inheritance
Syntax for INHERITING the features from base class to derived class:
class <clsname-2> extends <clsname-1>
{
Variable declaration;
Method definition;
};
Here, clsname-1 and clsname-2 represents derived class and base class respectively.
Extends is a keyword which is used for inheriting the data members and methods from base class to
the derived class and it also improves functionality of derived class.
For example:
class c1;
{
int a;
void f1()
{
…………;
}
};
class c2 extends c1
{
int b;
void f2()
{
…………;
}
};
Whenever we inherit the base class members into derived class, when we creates an object of
derived class, JVM always creates the memory space for base class members first and later memory
space will be created for derived class members.
18
Example:
Write a JAVA program computes sum of two numbers using inheritance?
Answer:
class Bc
{
int a;
};
class Dc extends Bc
{
int b;
void set (int x, int y)
{
a=x;
b=y;
}
void sum ()
{
[Link] ("SUM = "+(a+b));
}
};
class InDemo
{
public static void main (String k [])
{
Dc do1=new Dc ();
[Link] (10,12);
[Link] ();
}
};
Types of Inheritances
Single Inheritance: It means when a base class acquired the properties of super class
class Animal
{
void eat()
19
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
In this example base class is Dog and super class is Animal:
Multilevel Inheritance:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class, thereby making this derived class the base class for the new class. As you can see in below flow
diagram C is subclass or child class of B and B is a child class of A
Example:
Class X
{
public void methodX()
{
[Link]("Class X method");
}
}
20
Class Y extends X
{
public void methodY()
{
[Link]("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D
Example:
class A
{
public void methodA()
{
[Link]("method of Class A");
}
}
class B extends A
{
public void methodB()
{
21
[Link]("method of Class B");
}
}
class C extends A
{
public void methodC()
{
[Link]("method of Class C");
}
}
class D extends A
{
public void methodD()
{
[Link]("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
}
}
Output:
method of Class A
method of Class A
method of Class A
Multiple Inheritance:
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base classes.
22
Note: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
leads to problems in the hierarchy. This results in unwanted complexity when further extending the
class.
Hybrid Inheritance in Java
A hybrid inheritance is a combination of more than one types of inheritance. For example when class A
and B extends class C & another class D extends class A then this is a hybrid inheritance, because it is a
combination of single and hierarchical inheritance.
The diagram is just for the representation, since multiple inheritance is not possible in java
class C
{
public void disp()
{
[Link]("C");
}
}
class A extends C
{
public void disp()
{
[Link]("A");
}
}
class B extends C
{
public void disp()
{
[Link]("B");
}
class D extends A
{
23
public void disp()
{
[Link]("D");
}
public static void main(String args[]){
D obj = new D();
[Link]();
}
}
This example is just to demonstrate the hybrid inheritance in Java. Although this example is
meaningless, you would be able to see that how we have implemented two types of inheritance(single
and hierarchical) together to form hybrid inheritance.
Class A and B extends class C → Hierarchical inheritance
Class D extends class A → Single inheritance
Inhibiting Inheritance of Class Using Final
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context.
Final can be:
1. variable
2. method
3. class
The main purpose of using a class being declared as final is to prevent the class from being subclassed.
If a class is marked as final then no class can inherit any feature from the final class.
Example:
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
[Link]();
}
}
24
Output:
Compile time error
Since class Bike is declared as final so the derived class Honda cannot extend Bike
Access Control and Inheritance
Although a subclass includes all of the members of its superclass, it cannot access those members of the
superclass that have been declared as private.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new
B(); [Link](10,
12); [Link]();
[Link]("Total is " + [Link]);
}
}
This program will not compile because the reference to j inside the sum( ) method of B
causes an access violation. Since j is declared as private, it is only accessible by other members
of its own class. Subclasses have no access to it.
25
Application of Keyword Super
Super keyword is used for differentiating the base class features with derived class features.
Super keyword is placing an important role in three places.
variable level
method level
constructor level
Super at variable level:
Whenever we inherit the base class members into derived class, there is a possibility that
base class members are similar to derived class members.
In order to distinguish the base class members with derived class members in the derived
class, the base class members will be preceded by a keyword super.
For example:
class Bc
{
int a;
};
class Dc extends Bc
{
int a;
void set (int x, int y)
{
super.a=x;
a=y; //by default 'a' is preceded with 'this.' since 'this.' represents current class
}
void sum ()
{
[Link] ("SUM = "+(super.a+a));
}
};
class InDemo1
{
public static void main (String k [])
{
Dc do1=new Dc ();
[Link] (20, 30);
[Link] ();
}
};
26
Super at method level:
Whenever we inherit the base class methods into the derived class, there is a possibility that
base class methods are similar to derived methods.
To differentiate the base class methods with derived class methods in the derived class, the
base class methods must be preceded by a keyword super.
Syntax for super at method level: super. base class method name
For example:
class Bc
{
void display ()
{
[Link] ("BASE CLASS - DISPLAY...");
}
};
class Dc extends Bc
{
void display ()
{
[Link] (); //refers to base class display method
[Link] ("DERIVED CLASS- DISPLAY...");
}
};
class InDemo2
{
public static void main (String k [])
{
Dc do1=new Dc ();
[Link] ();
}
};
Constructor Method and Inheritance
Super at constructor level:
super() can be used to invoke immediate parent class constructor.
class A
{
int i,j;
A(int a,int b)
{
i=a;
j=b;
27
}
void show()
{
[Link]("i and j values are"+i+" "+j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);//super class constructor
k = c;
}
// display k – this overrides show() in A
void show()
{
[Link]();
[Link]("k: " + k);
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
Abstract Classes:
In JAVA we have two types of classes. They are concrete classes and abstract classes.
• A concrete class is one which contains fully defined methods. Defined methods are also known
as implemented or concrete methods. With respect to concrete class, we can create an object of
that class directly.
28
An abstract class is one which contains some defined methods and some
undefined methods. Undefined methods are also known as unimplemented
or abstract methods. Abstract method is one which does not contain any
definition.
To make the method as abstract we have to use a keyword called abstract before
the function declaration.
Syntax for ABSTRACT CLASS: abstract return_type method_name (parameters list);
// A Simple demonstration of
abstract. abstract class A
{
abstract void callme();
// concrete methods are still allowed in
abstract classes void callmetoo()
{
[Link]("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
[Link]("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B(); [Link](); [Link]();
}
}
Notice that no objects of class A are declared in the program. As mentioned, it is not
possible to instantiate an abstract class.
29