Java Classes, Objects, and Methods Guide
Java Classes, Objects, and Methods Guide
UNIT – II
CLASS [2 Marks]
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
class <class_name>
{
data member; //properties
method; // behavior
}
Method in Java
Advantage of Method
• Code Reusability
• Code Optimization
new keyword
Fields Declaration
Class Student
{
Int Rno;
String name;
}
Method Declaration
Type methodname(parameter-list)
{
Method Body;
}
[Link]
JAVA
class Student
{
i
n
t
R
n
o
;
S
tr
i
n
g
n
a
m
e;
n
a
m
e
=
n
;
}
}
Object in Java
OBJECT
An object is a real time entity that has properties and behavior is known as an object e.g.
[Link]
JAVA
chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengibleAnobject has
three characteristics: [2
Marks]
Let us now look deep into what are objects. If we consider the real-world we can find manyobjects
around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,wagging, running
If you compare the software object with a real world object, they have very similar characteristics.
Software objects also have a state and behavior. A software object's state is stored in fieldsand
behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-to- object
communication is done via methods.
Classes in Java:
class Dog
{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
[Link]
JAVA
Example of creating an object is given below:
class Puppy{
Puppy(String name){
// This constructor has one parameter, name.
[Link]("Passed Name is :" + name );
}
Instance variables and methods are accessed via created objects. To access an instance variable the fully
qualified path should be as follows:
In this example, we are creating the two objects of Student class and initializing the value to these objects
by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects by
invoking the displayInformation method.
class Student2
{
int rollno;
String name;
void displayInformation()
{
[Link](rollno+" "+name);
}
}
class Stud
{
public static void main(String args[])
{
[Link]
JAVA
Student2 s1=new Student2();
Student2 s2=new Student2();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
111 Karan
222 Aryan
If we compile and run the above program, then it would produce the following result:
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
[Link]
JAVA
2. Parameterized constructor
1 Default Constructor
A constructor that has no parameter is known as default constructor. Syntax of
default constructor:
<class_name>()
{
class Bike1
{
Bike1()
{
[Link]("Bike is created");
}
}
[Link]
JAVA
class DefaultConstructor
{
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor. default
constructor
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
[Link] 0 and null values are provided by default constructor.
[Link]
JAVA
2 parameterized constructor
A constructor that has parameters is known as parameterized constructor.
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){[Link](id+" "+name);
}
class ParameterizedConstructor
{
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
[Link]
JAVA
class Calculator
{
int a,b;
double d;
Calculator()
{
a=0;
b=0;
[Link]("The addition of " +a+ "+" +b+ " = " +(a+b));
}
Calculator(int x,int y)
{
a=x;
b=y;
[Link]("The addition of " +a+ "+" +b+ " = " +(a+b));
}
class ConstructorOverload
{
public static void main(String args[])
{
Calculator obj1=new Calculator(); Calculator
obj2=new Calculator(10,20); Calculator
obj3=new Calculator(35.6,10,20);
}
}
OUTPUT
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java ConstructorOverload
The addition of 0+0 = 0
The addition of 10+20 = 30
The addition of 35.6+10+20 = 65.6
[Link]
JAVA
The methods that have the same name but differs in parameter list is called method overloading.
Method overloading is used when objects are required to perform similar tasks but using different input
parameters.
class Geometry
{
double width,height; int
radius;
void area(int x)
{
radius=x;
double area=3.142*radius*radius;
[Link]("Area of Circle is = "+area);
}
}
class Overloading
{
public static void main(String args[])
{
Geometry g=new Geometry();
[Link](10.2,15.3);
[Link](5);
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java Overloading
Area of Rectangle is = 156.06
Area of Circle is = 78.55
[Link]
JAVA
The static keyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of
the class.
• The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
• The static variable gets memory only once in class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get memory each time
when object is created. All students have its unique rollno and name so instance data member is good.
Here, college refers to the common property of all objects. If we make it static, this field will get memory
only once.
[Link]
JAVA
Student(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno+" "+name+" "+college);
}
}
class StaticVariable
{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan BCA
222 Aryan BCA
[Link]
JAVA
class Student
{
int rollno;
String name;
static String college = "ITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno+" "+name+" "+college);
}
}
class StaticMethod
{
public static void main(String args[])
{
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output: 111 Karan BCA
222 Aryan BCA
[Link]
JAVA
class Calculate{
static int cube(int x){
return x*x*x;
}
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
Ans) because object is not required to call static method if it were non-static method, jvm create object
first then call main() method that will lead the problem of extra memory allocation.
[Link]
JAVA
class A2
{
static
{
[Link]("static block is invoked");
}
}
class StaticBlock
{
public static void main(String args[])
{
[Link]("Hello main");
}
}
[Link]
JAVA
INHERITANCE [5 or 10 Marks]
Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple inheritance.
class Parent
{
.....
.....
}
When a one class extends another one class only then we call it a single inheritance.
The below flow diagram shows that class B extends only one class which is A. Here A is a parent class
of B and B would be a child class of A.
[Link]
JAVA
class A
{
public void methodA()
{
[Link]("Base class method");
}
}
Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java SingleInheritance
Base class method
Child class method
[Link]
JAVA
Multilevel inheritance The derived class inherits from one Base class, which intern inherits from some
other class is called multilevel inheritance in Java.
class A
{
void methodA()
{
[Link]("Class A method");
}
}
class B extends A
{
void methodB()
{
[Link]("Class B method");
}
}
class C extends B
{
void methodC()
{
[Link]("Class C method");
}
}
[Link]
JAVA
class MultilevelInheritance
{
public static void main(String args[])
{
C obj = new C();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling child class method
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java MultilevelInheritance Class A
method
Class B method
Class C method
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.
Parent class have two or more than two child class then we call it as Hierarchical Inheritance.
[Link]
JAVA
class B extends A
{
void methodB()
{
[Link]("Class B method");
}
}
class C extends A
{
void methodC()
{
[Link]("Class C method");
}
}
class D extends A
{
void methodD()
{
[Link]("Class D method");
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
[Link](); //calling Parent class methodA
[Link](); //calling Child class methodB
[Link](); //calling Parent class methodA
[Link](); //calling Child class methodC
[Link](); //calling Parent class methodA
[Link](); //calling Child class methodD
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java HierarchicalInheritance Class A
method
Class B method
Class A method
Class C method
Class A method
Class D method
[Link]
JAVA
C++ and few other languages supports multiple inheritance while java doesn’t support it. It is just to
remove ambiguity, because multiple inheritance can cause ambiguity in few scenarios. One of the most
common scenario is Diamond problem.
class Object is a Parent class of all the classes in java. So when you create a class the class Object is
automatically added in the program and diamond shape in multiple inheritance.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance.
A typical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a same
way as multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can
have multiple as well as hybrid inheritance in Java.
Yes and No. If you are using only classes then this is not allowed in java, however using interfaces it’s
possible to have hybrid inheritance in java. We will see this in below example programs.
[Link]
JAVA
Yes, Hierarchical inheritance is different than hybrid inheritance. Hierarchical inheritance is possible to
have in java even using the classes alone itself as in this type of inheritance two or more classes have the
same parent class or in other words a single parent class has two or more child classes, which is quite
possible to have in java.
class B extends A
{
void methodA()
{
[Link]("Child class B is overriding inherited method A");
}
void methodB()
{
[Link]("Class B methodB");
}
}
class C extends A
{
void methodA()
{
[Link]("Child class C is overriding the methodA");
}
[Link]
JAVA
void methodC()
{
[Link]("Class C methodC");
}
}
class D extends B, C
{
void methodD()
{
[Link]("Class D methodD");
}
}
class HybridIneritance
{
public static void main(String args[])
{
D obj1= new D();
[Link]();
[Link]();
}
}
Output:
Error!!
Why? Most of the times you will find the following explanation of above error – Multiple inheritance is
not allowed in java so class D cannot extend two classes(B and C). But do you know why it’s not
allowed? Let’s look at the above code once again, In the above program class B and C both are extending
class A and they both have overridden the methodA(), which they can do as they have extended the class
A. But since both have different version of methodA(), compiler is confused which one to call when
there has been a call made to methodA() in child class D (child of both B and C, it’s object is allowed to
call their methods), this is a ambiguous situation and to avoid it, such kind of scenarios are not allowed in
java.
[Link]
JAVA
In other words, If subclass provides the specific implementation of the method that has been provided by
one of its parent class, it is known as method overriding.
class Animal
{
void eat()
{
[Link]("Animal is eating");
}
}
[Link]
JAVA
class Overriding
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java Overriding
Dog is eating
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
[Link]
JAVA
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java OverrideDemo
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
[Link]
JAVA
Dynamic method dispatch is a technique which enables us to assign the base class reference to a child class
object. As you can see in the below example that the base class reference is assigned to child class object.
Lab Program : 6
class Base
{
void display()
{
[Link]("I am in Base Class Display Method");
}
}
class DynamicDispatch
{
public static void main(String args[])
{
Base obj=new Child();
[Link]();
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java DynamicDispatch
I am in Child Class Display Method
[Link]
JAVA
class Parent
{
void display1()
{
[Link]("I am in Parent Class Display Method");
}
void display2()
{
[Link]("I am in Parent Class Display2 Method");
}
}
Note: In dynamic method dispatch the object can call the overriding methods of child class and all the
non-overridden methods of base class but it cannot call the methods which are newly declared in the child
class. In the above example the object obj was able to call the dispplay1()(overriding method) and
display2()(non-overridden method of base class). However if you try to call the disp() method (which has
been newly declared in Test class) [[Link]()] then it would give compilation error with the following
message:
Exception in thread "main" [Link]: Unresolved compilation
problem: The method disp() is undefined for the type Parent
[Link]
JAVA
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
All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses
from overriding the superclass, we declare them as final using the keyword final
Making a method final ensures that the functionality defined in this method will never be altered in any
way.
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
class Bike
{
final int speedlimit=90;//final variable void
run()
{
speedlimit=400;
}
}
class FinalVariable
{
public static void main(String args[])
{
Bike obj=new Bike();
[Link]();
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
[Link][Link] error: cannot assign a value to final variable speedlimit
speedlimit=400;
^1
error
[Link]
JAVA
class Bike
{
final void run()
{
[Link]("running");
}
}
Output
C:\Program Files\Java\jdk1.7.0_03\bin>javac [Link]
[Link][Link] error: run() in Honda cannot override run() in Bike
void run()
^
overridden method is final 1
error
[Link]
JAVA
class FinalClass
{
public static void main(String args[])
{
Honda h= new Honda();
[Link]();
}
}
Output
C:\Program Files\Java\jdk1.7.0_03\bin>javac [Link]
[Link][Link] error: cannot inherit from final Bike
class Honda extends Bike
^
1 error
Example
class Bike
{
void run()
{
[Link]("Running...");
}
}
[Link]
JAVA
class FinalInheritance
{
public static void main(String args[])
{
Honda h= new Honda()
[Link]();
}
}
Output
Running…
[Link]
JAVA
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it
is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
• It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
• It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
The finalize() method is invoked each time before the object is garbage collected. This method can be used
to perform cleanup processing. This method is defined in Object class as:
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found
in System and Runtime classes.
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
[Link]
JAVA
By making a method final we ensure that the method is not get inherited in subclass. But by making
method abstract we compulsory override it.
A class that is declared using “abstract” keyword is known as abstract class. It may or may not include
abstract methods which means in abstract class you can have concrete methods (methods with body) as well
along with abstract methods ( without an implementation, without braces, and followed by a semicolon).
An abstract class can not be instantiated (you are not allowed to create object of Abstract class).
of Abstract Method
abstract class Demo1
{
public void disp1()
{
[Link]("Concrete method of abstract class");
}
abstract void disp2();
}
[Link]
JAVA
void disp2()
{
[Link]("I'm overriding abstract method");
}
}
class AbstractMethod
{
public static void main(String args[])
{
Demo2 obj = new Demo2();
obj.disp2();
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java AbstractMethod
I'm overriding abstract method
[Link]
JAVA
ARRAYS [2 or 5 or 10 Marks]
Array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store
similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.
[Link]
JAVA
A list of items can be given one variable name using only one subscript and such a variable is called One
Dimensional Array.
Syntax :
Array[0]
Array[1]
Array[2]
Array[3]
Array[4]
Creating an Array
1. Declaration of Array
Example :
1. int [] number;
2. int []marks;
3. int students[];
Creation of Arrays
After declaring an array, we need to create it in the memory. Java allows us to create array using
new operator.
[Link]
JAVA
Ex :
Initialization of Arrays
The final step is to put values into the array created. This process is known as initialization.
Example :
Array[0]=10;
Array[1]=20;
Array[2]=30;
Array[3]=40;
Array[4]=50;
We can declare, instantiate and initialize the java array together by:
class OneDimentional
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0;i<[Link];i++)
{
[Link](a[i]);
}
}
}
[Link]
JAVA
[Link]
JAVA
[Link]
JAVA
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java TwoDArray Enter
row and column
2
2
Enter Array Elements
11
23
14
21
The Array Elements are
11 23
14 21
[Link]
JAVA
STRING [2 Marks]
String is a sequence of characters. But in java, string is an object that represents a sequence of characters.
String class is used to create string object.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
[Link]
JAVA
In the above example only one object will be created. Firstly JVM will not find any string object with the
value "Welcome" in string constant pool, so it will create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create new object but will return the reference to the same
instance.
Note: String objects are stored in a special memory area known as string constant pool. Why
To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).
2) By new keyword
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non
pool).
Example
[Link](s1);
[Link](s2);
[Link](s3);
}
}
Output
java
strings
example
[Link]
JAVA
The [Link] class provides many useful methods to perform operations on sequence of char
values.
[Link]
JAVA
class StringDemo
{
public static void main(String args[])
{
String s1="Bachelor";
String s2="Of";
String s3="Computer";
String s4="Application";
[Link]([Link]());
[Link]([Link]());
[Link]([Link](s4));
[Link]([Link]());
[Link]([Link](2));
[Link]([Link]('c'));
[Link]([Link]('f','o'));
[Link]([Link](5));
[Link]([Link](0,3));
[Link]([Link](s4));
[Link]([Link](s2));
[Link]([Link]("App"));
[Link]([Link]("or"));
}
}
Output
C:\Program Files\Java\jdk1.7.0\bin>javac [Link]
C:\Program Files\Java\jdk1.7.0\bin>java StringDemo
BACHELOR
bachelor
ComputerApplication
11
c
2
Oo
lor
App
1
false
true
true
[Link]
JAVA
There are many differences between String and StringBuffer. A list of differences between String and
StringBuffer are given below:
String is slow and consumes more memory when you concat StringBuffer is fast and consumes less
2) too many strings because every time it creates new instance. memory when you cancat strings.
[Link]
JAVA
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just need one
that can change sizes over the lifetime of a program.
Wrapper class in java provides the mechanism to convert primitive data types into object and object into
primitive data types.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa
unboxing.
The eight classes of [Link] package are known as wrapper classes in java. The list of eight wrapper
classes are given below:
Output:
20 20 20
[Link]
JAVA
Output:
333
[Link]