Java Classes and Objects Explained
Java Classes and Objects Explained
Class:
Class defines a new data type that can be used for creating objects.
Declaration of class:
In JAVA language, class declaration can be done by using the following syntax.
Syntax:
class classname
{
datatype instance_var1;
datatype instance_var2;
.
.
datatype instance_varn;
returntype methodname1(parameter_list)
{
//body
}
.
.
returntype methodnamen(parameter_list)
{
//body
}
}
Variables which are declared inside a class are called as instance variables. Because
each instance of a class can hold a separate copy of these variables.
Class also contains n number of methods which are used to perform operations on data.
Variables and methods which are defined inside a class are collectively known as
members of a class.
Example:
class Box
{
}
After defining a class, by using that class we can create any number of objects.
Creation of Object:
In first step, class variable is created or declared by using the class name.
Syntax:
classname class_var;
In second step, the memory is allocated for an object at run time using new operator.
Syntax:
Class_var=new classname();
If the programmer not writing any constructor in a class, then JAVA compiler provides
one default constructor.
The above two steps are combined into a single statement as follows.
Example:
After creating objects, we can access the class members using those objects.
Syntax:
[Link]=value;
To call and execute any method in a class, the following syntax is used.
Syntax:
[Link]();
Write a program to illustrate the use of class and objects.
class Box
class BoxDemo
double vol;
[Link]=15.35;
[Link]= 20.56;
[Link]=10.34;
vol=[Link]*[Link]*[Link];
[Link](“Volume is “+vol);
returntype method_name(parameter_list)
{
//body of the method
}
Here returntype represents the type of the data returned by the method. This can be
any valid type including class types that we create.
If the method does not return a value, its return type must be void.
Example:
In the above example program, we are calculating volume of a box in BoxDemo class.
Now we are calculating the volume of a box in Box class by adding method to Box class.
class Box
void volume()
[Link](“Volume is “+ (width*height*depth));
class BoxDemo
[Link]=10.25;
[Link]=20.35;
[Link]=15.45;
[Link]=3.45;
[Link]=6.78;
[Link]=9.85;
[Link]();
[Link]();
}
Output:
Volume is 3222.676875
Volume is 230.40135
class Box
double volume()
return width*height*depth;
class BoxDemo
double vol;
[Link]=10.25;
[Link]=20.35;
[Link]=15.45;
[Link]=3.45;
[Link]=6.78;
[Link]=9.85;
vol=[Link]();
[Link](“Volume is “+vol);
vol=[Link]();
[Link](“Volume is “+vol)
Output:
Volume is 3222.676875
Volume is 230.40135
class Box
double volume()
width=w;
height=h;
depth=d;
class BoxDemo
{
Box b1=new Box();
double vol;
[Link](2.35,4.65,6.78);
[Link](5.67, 7.89,8.97);
vol=[Link]();
[Link](“Volume is “+vol);
vol=[Link]();
[Link](“Volume is “+vol);
Volume is 401.28461100000004
Overloaded Methods:
In JAVA language, it is possible to define two or more methods within a same class with
same name but with different number and/or types of arguments.
Then the methods are said to be overloaded and the process is referred as method
overloading.
When overloaded method is invoked, JAVA compiler uses the type and/or number of
arguments to determine the method which is to be executed.
class OverLoad
void display()
[Link](“No Parameters”);
void display(int a)
{
[Link](“a= “+a);
double display(double a)
[Link](“double a= “+a);
return a*a;
class OverLoadDemo
[Link]();
[Link](10);
[Link](10,20);
double result=[Link](3.5);
[Link](“Result= “+result);
}
Output: No Parameters
a= 10
a= 10 b= 20
double a= 3.5
Result= 12.25
In some cases, JAVA’s automatic type conversion can play a role in overloaded
resolution.
class OverLoad
void display()
[Link](“No Parameters”);
void display(double a)
[Link](“double a=”+a);
class OverLoadDemo
[Link]();
[Link](10,20);
[Link](10);
[Link](15.65);
}
Output:
No Parameters
a= 10b= 20
double a=10.0
double a=15.65
Here we are not defined a method display(int) in OverLoad class. Therefore when a
displaly() is called with an integer argument in OverLoadDemo, no matching method is
found. However, JAVA can automatically converts integer to double and this conversion can
be used to resolve the call.
Recursive methods:
import [Link].*;
class Factorial
{
int fact(int n)
{
if(n==0||n==1)
return 1;
else
return n*fact(n-1);
}
}
class Recursion
{
public static void main(String args[])
{
int val;
Factorial f=new Factorial();
Scanner sc=new Scanner([Link]);
[Link](“enter one number”);
val=[Link]();
[Link](“Factorial of “+val+”is ”+[Link](val));
}
}
Output:
enter one number
5
Factorial of 5is 120
Constructors:
Note: When constructor is not defined in a class, JAVA compiler provides one default
constructor to a class automatically. The default constructor automatically initializes the
instance variables to their default values.
Types of constructors:
Zero-argument constructor:
Syntax:
classname()
{
//body of the constructor
}
Example:
class Box
Box()
width=10.25;
height=12.35;
depth=15.45;
double volume()
return width*height*depth;
class ConstructorDemo
double vol;
vol=[Link]();
[Link](“Volume is “+vol);
vol=[Link]();
[Link](“Volume is “+vol);
Parameterized Constructor:
While the Box() constructor in the previous program does initialize a Box object, it is
not very useful because all the boxes have same dimensions.
classname(parameter_list)
{
//body of the constructor
}
Example:
class Box
width=w;
height=h;
depth=d;
double volume()
return width*height*depth;
class ConstructorDemo
double vol;
vol=[Link]();
[Link](“Volume is “+vol);
vol=[Link]();
[Link](“Volume is “+vol);
Constructor overloading:
Sometimes there is a need of initializing an object in different ways. This can be done
using constructor overloading.
Constructor overloading means writing two or more constructors with different types
or number of parameters.
Example:
class Box {
double width, height, depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
Box() {
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
class Test {
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}
Output: Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
When a member is declared static, it can be accessed before any objects of its class
arecreated and without reference to any object.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
To call a static method from outside its class, we use class name and dot operator
as follows.
[Link]();
o
o Here classname is the name of the class in which static method is declared.
o In the same way, static variable can be accessed by using its class name and dot
operator as follows.
classname.variable_name;
o
Note: Methods declared as static have several [Link] can only call other static methods.
Then can only directly access static variables.
class Student{
int rollno;
String name;
static String college = "BITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display(){
[Link](rollno+" "+name+" "+college);
}
}
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}
Output:
111 Karan VIT
222 Aryan VIT
333 Sonoo VIT
Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading
class Demo{
static int count;
static void count()
{
count++;
[Link](count);
}
static
{
count=1;
[Link](count);
}
}
class D{
public static void main(String[] args)
{
[Link]();
[Link]();
}
}
OUTPUT:
1
2
3
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
There are four types of Java access modifiers:
3) protected (accessible only to classes that subclass your class directly within the
1) public
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
To understand public and private access modifiers, consider the following program.
class Test
{
int a=22;
public int b=10;;
private int c=20;
protected int x=100;
int getc()
{
return c;
}
}
class AccessTest
{
public static void main(String args[]) {
Test ob = new Test();
[Link](ob.a);
[Link](ob.b);
int res=[Link]();
//[Link](ob.c); //error
[Link](res);
[Link](ob.x);
}
}
Output: 22
10
20
100
this keyword:
In Java, this is a keyword which is used to refer current object of a class. We can use it
to refer any member of the class. It means we can access any instance variable and
method by using this keyword.
The main purpose of using this keyword is to solve the confusion when we have same
variable name for instance and local variables.
Output: 16
Square(int side)
{
[Link] = side;
}
void display(){
[Link](side*side);
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square();
[Link]();
}
}
Output: 400
c) Accessing method using this keyword: You may invoke the method of the current class by using
the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class Square
{
int side;
Square(int side)
{
[Link] = side;
}
void getarea(){
[Link](side*side);
}
void display(){
[Link](); // same as getarea();
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square(2);
[Link]();
}
}
[Link] = side;
[Link]([Link]*[Link]);
area(this);
[Link]([Link]*[Link]);
}
void area(Square x)
{
[Link]=7;
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square(2);
}
}
Output:
4
49
Inheritance in JAVA:
Inheritance is the process by which one object acquires the properties of another object.
(or)
Superclass (or) Parent class (or) base class: A class that is inherited is called as
superclass.
Subclass (or) Child class (or) derived class: A class that does inheriting is called as
subclass.
Types of inheritance:
Generally there are 5 types of inheritance
They are
1) Single inheritance
2) Multiple inheritance
3) Multi-level inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
Single inheritance:
Deriving a sub class from single super class is called as single inheritance
Multiple inheritance:
Deriving a sub class from more than one super class is called as multiple inheritance.
Note: JAVA does not support multiple inheritance directly. We can achieve multiple
inheritance in JAVA by using interfaces.
Multi-level inheritance:
In multi-level inheritance, one sub class is derived from another sub class. Hence one
sub class becomes super class for a new class.
Hierarchical inheritance:
Deriving more than one sub class from a single super class is called as hierarchical inheritance.
Hybrid inheritance:
In JAVA language, in order to derive a class from another class we use extends keyword.
Syntax:
Iam in class B
class A{
void display1(){
[Link]("Iam in class A");
}
}
class B extends A{
void display2(){
[Link]("Iam in class B");
}
}
class C extends A{
void display3(){
[Link]("Iam in class C");
}
}
class Demo{
public static void main(String[] args){
C ob=new C();
ob.display1();
ob.display3();
}
}
Output:
Iam in class A
Iam in class C
super keyword:
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of
the keyword super. The keyword “super” came into the picture with the concept of
Inheritance.
super keyword (in sub class) is to access the hidden members of its immediate super class. To
understand this let’s consider the following example:
class A
{
int x;
public void display()
{
[Link]("This is display in A");
}
}
class B extends A
{
int x=10;
public void display()
{
[Link]("Value of x in A is: "+ super.x); //parent class varaible
[Link](); //parent class method
[Link]("This is display in B");
}
}
class Driver
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}
Output:
Value of x in A is: 0
This is display in A
This is display in B
A subclass can call a constructor defined by its superclass by using the following syntax.
Syntax:
super(arg_list);
Here arg_list specifies any arguments needed by the constructor in the superclass.
super() must always be the first statement executed inside a subclass constructor.
class Person{
int id;
String name;
Person(int id,String name){
[Link]=id;
[Link]=name;
float salary;
[Link]=salary;
void display(){
class TestSuper5{
[Link]();
}
}
Output:
1 ankit 45000.0
Polymorphism in Java
Polymorphism in Java can be done in two ways, method overloading and method
overriding. There are two types of polymorphism in Java.
1. Compile-time polymorphism
2. Runtime polymorphism.
Compile Time Polymorphism:
Whenever an object is bound with its functionality at the compile time, this is known as the
compile-time polymorphism.
At compile-time, java knows which method to call by checking the method signatures. So this
is called compile-time polymorphism or static or early binding.
Compile-time polymorphism is achieved through method overloading.
Method Overloading says you can have more than one function with the same name in one
class having a different prototype.
Method overriding:
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the super class.
When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by
the super class will be hidden.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
[Link]("subclass method");
}
}
class OverridingDemo
{
public static void main(String args[])
{
B b1=new B();
[Link]();
}
}
Output: subclass method
Note: To call method defined by superclass , the keyword super is used in subclass method.
class A
{
void show()
{
[Link]("superclass method");
}
}
class B extends A
{
void show()
{
[Link]();
[Link]("subclass method");
}
}
class OverridingDemo
{
public static void main(String args[])
{
B b1=new B();
[Link]();
}
}
Output:
superclass method
subclass method
class A
{
void show()
{
[Link]("super class method");
}
}
class B extends A
{
void show()
{
[Link]("sub class1 method");
}
}
class C extends B
{
void show()
{
[Link]("sub class2 method");
}
}
class Demo{
public static void main(String args[])
{
A a1=new A();
A b1=new B();
A c1=new C();
[Link]();
[Link]();
[Link]();
}
}
Output: super class method
sub class1 method
sub class2 method
Abstract methods can be declared using the keyword ‘abstract’ by using the following
syntax
Example:
Abstract class: Any class which contains at least one abstract method is called as
abstract class.
To declare abstract class, the keyword ‘abstract’ is used before the class declaration.
Syntax:
In abstract class, in addition to abstract methods, concrete methods are also available.
Abstract methods should be implemented in the sub classes of abstract class. If sub class
also not implemented abstract method then make the sub class also as abstract.
Write a java program for abstract class to find areas of different shapes
//Program to find areas of different shapes using abstract class
abstract class Shape
{
int dim1,dim2;
Shape(int dim1,int dim2)
{
this.dim1=dim1;
this.dim2=dim2;
}
abstract double area();
}
class Triangle extends Shape
{
Triangle(int a,int b)
{
super(a,b);
}
double area()
{
double a1=(dim1*dim2)/2;
return a1;
}
}
class AbstractDemo
{
public static void main(String args[])
{
Shape s;
Triangle t=new Triangle(10,20);
s=t;
[Link]([Link]());
}
}
Output: 100
Final keyword:
Final variables:
Once we declare a variable with the final keyword, we can’t change its value again. If we
attempt to change the value of the final variable, then we will get a compilation error.
You can initialize a final variable when it is declared. A final variable is called blank
final variable, if it is not initialized while declaration.
We can initialize a blank final variable inside the constructor of the class.
Example:
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
[Link]("Age: " + AGE);
}
}
final methods:
If we try to override final method, then it will give compile time error.
Example
class A
{
[Link](“final method”);
class B extends A
Final classes:
Example:
final class A
{
void show()
void show()
Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
The argument list should be different The argument list should be the same in method
while doing method overloading. overriding