1
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to initialize the object.
If the class doesn’t hava any constructor ,then java compiler creates a default constructor.
Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type
Syntax of default constructor:
<class_name>()
{ }
Ex.
class Demo
Demo()
System.out.println(“hai this is default constructor”);
}
2
class DemoFirst
{ public static void main(String args[])
Demo d=new Demo();
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Ex:
class Demo
{
int x;
Demo(int i)
{
x=i;
}
}
class DemoTwo
{
public static void main(String args])
{
Demo d=new Demo(10);
System.out.println(“the value of x=”+d.x);
}
}
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
3
Ex:
class Demo
int x;
Demo()
System.out.println(“this is defalut constructor”);
System.out.println(“the value of x=”+x);
Demo (int s)
x=s;
System.out.println(“this is parameterized constructor”);
System.out.println(“the value of x=”+x);
} }
Class DemoThree
{ public static void main(String args[])
Demo d1=new Demo();
Demo d2=new Demo(10);
} }
Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.There are many ways to copy the values of one object
into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
4
By using constructor:
class Demo
int x;
Demo(int p)
x=p;
System.out.println(“this is parameterized constructor”);
System.out.println(“the value of x=”+x);
Demo (Demo d)
{ x=d.x;
System.out.println(“this is copy constructor”);
System.out.println(“the value of x=”+x);
} }
Class DemoFour
{ Public static void main(String args[])
Demo d1=new Demo(10);
Demo d2=new Demo(d1);
}
5
By assing the values of one object to another
class Demo
int x;
Demo(int p)
x=p;
Demo()
void display()
System.out.println(“the value of x=”+x);
Class DemoFive
Public static void main(String args[])
Demo d1=new Demo(10);
d1.display();
Demo d2=new Demo();
d2.x=d1.x;
d2.display()
} }
6
this keyword:
there can be a lot of usage of this keyword. In java, this is a reference variable that
refers to the current object.
Usage of java this keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
this: to refer current class instance variable
class Demo
{ int x;
Demo(int x)
{ this.x=x;
void display()
{ System.out.println(“the value of x=”+x);
class Demothis
{ public static void main(String args[])
Demo d=new Demo();
d.display();
}
7
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use
this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
class A{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
this.m();
}
}
class TestThis
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
class A
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
8
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A(10);
}
}
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocksThe static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
Java static variable
If you declare any variable as static, it is known as a static variable.
A static variable is declared inside the class ,outside the method,block,constructor.
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the method area at the time of class
loading.
o If we are not initialize the static variable,jvm will initialize with default values.
Advantage of static variable
It makes your program memory efficient (i.e., it saves memory).
class Student{
int rollno;
String name;
static int cc 1161;
9
Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+cc);}
}
class TestStatic1
{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
static method
If you apply static keyword with any method, it is known as static method.
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.
Example of static method
class Student
{
int rollno;
String name;
static int cc =1161;
static void change()
{
cc=2112;
}
Student(int r, String n){
10
rollno = r;
name = n;
}
void display()
{ System.out.println(rollno+" "+name+" "+cc);
}
}
class TestStatic2
{
public static void main(String args[]){
Student.change();
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Example of static block
class A2{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}}
11
Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
To make object be unreferenced
o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
3) By anonymous object:
new Employee();
finalize() method
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:
protected void finalize(){}
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.
12
public static void gc(){}
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Java Arrays
Array is a collection of similar type of elements which have a contiguous memory location
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on..
In Java all arrays are dynamically allocated.
Since arrays are objects in Java, we can find their length using member length
Array can contains primitives data types as well as objects of a class depending on the
definition of array. In case of primitives data types, the actual values are stored in
contiguous memory locations. In case of objects of a class, the actual objects are stored in
heap segment.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the 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 which
grows automatically.
Creating, Initializing, and Accessing an Array
13
One-Dimensional Arrays
The general form of a one-dimensional array declaration is
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};
ex.
class Testarray1
{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
Multidimensional Array in Java
data is stored in row and column based index (also known as matrix form).
Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
14
Example to instantiate Multidimensional Array in Java
1. int[][] arr=new int[3][3];
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
public class TestAnonymousArray{
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
15
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});
} }
Program for Adition of 2 Matrices in Java
class Testarray{
public static void main(String args[]){
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();}
}}
Java Inner Classes
In Java, it is also possible to nest classes (a class within a class). The purpose
of nested classes is to group classes that belong together, which makes your
code more readable and maintainable.To access the inner class, create an
object of the outer class, and then create an object of the inner class:
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
16
public class MyMainClass {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
example of command-line argument in java
class CommandLineExample{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
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).
Usage of inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
17
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 Sub extends Super {
.....
.....
} The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.
Example :single inheritance
class Animal{
void eat()
{System.out.println("eating...");}
18
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multi level inheritance
When a class extends a class, which extends another class then this is called multilevel
inheritance. For example class C extends class B and class B extends class A then this type
of inheritance is known as multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
19
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance
When more than one classes inherit a same class then his is called hierarchical inheritance.
For example class B, C and D extends the same class A
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
20
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
Dog d=new Dog();
d.bark();
d.eat();
}}
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{
public static void main(String args[]){
C obj=new C();
obj.msg();
}
}
Compile Time Error
21
The super keyword
It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super
keyword as shown below.
super.variable
super.method();
super can be used to access parent class variables
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
class Animal{
void eat(){System.out.println("eating...");}
22
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Is -A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how
the extendskeyword is used to achieve inheritance.
public class Animal {
}
public class Mammal extends Animal {
23
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, based on the above example, in Object-Oriented terms, the following are true −
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the
properties of the superclass except for the private properties of the superclass.