Constructors - This - Inherit in Java PDF
Constructors - This - Inherit in Java PDF
Constructors - This - Inherit in Java PDF
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.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in
Java.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Explanation: In the above class, you are not creating any constructor so compiler provides
you a default constructor. Here 0 and null values are provided by default constructor.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of A method is used to expose the behaviour of an
an object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any constructor any case.
in a class.
The constructor name must be same as the The method name may or may not be same as
class name. the class name.
Java 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
In this example, we are going to copy the values of one object into another
using Java constructor.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
111 Karan
Copy the values of one object into another by assigning the values of one
object into another:
class copy
{ int x;
copy(int a){x=a;}}
cp=cp1;
System.out.println(cp.x);
System.out.println(cp1.x);}}
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and formal parameters, this keyword resolves the problem of
ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
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. Let's see
the example.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
OUTPUT: hello n
hello m
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();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Output:
5
hello a
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output:
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:
class Test
{
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
In event handling (or) in a situation where we have to provide reference of a class to another
one. It is used to reuse one object in many methods.
We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:
class B{
A obj;// Class with object of Class A as its data member
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A{
int data=10;
A(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A aa=new A();
}
}
OUTPUT: 10
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}}
A5@22b3ea59
A5@22b3ea59
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviours of a parent object. It is an important part of OOPs (Object Oriented
programming system).
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.
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.In the
terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}
OUTPUT:
Programmer salary is:40000
Bonus of Programmer is:1000
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
void eat(){System.out.println("eating...");}
}
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();
}}
Output:
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
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();
}}
Output:
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result); }}
Polymorphism in Java
Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one interface and
have multiple implementations. The word “poly” means many and “morphs”
means forms, So it means many forms.
Real life example of polymorphism: A person at the same time can have
different characteristic. Like a man at the same time is a father, a husband, an
employee. So the same person possess different behaviour in different
situations. This is called polymorphism.
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
In Java, Method Overloading is not possible by changing the return type of the
method only. That means return type of the method doesn’t play any role.
import java.util.*;
class overload
{
void Add()
System.out.println("Eneter a number");
int x=sc.nextInt();
System.out.println("Eneter a number");
int y=sc.nextInt();
System.out.println("Result="+(x+y));
{return(x+y+z);}
{return(x+y);}
class OverloadDemo
ob1.Add();
//int res=ob1.Add(10,20,30);
//float res1=ob1.Add(3.5f,2.5f);
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
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.
class TestOverloading{
public static void main(String[] args){System.out.println("HELLO JAVA");}
public static void main(String args){System.out.println("HII");}
public static void main(){System.out.println("HELLO WORLD");}
}
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int, long, float or double. The char
datatype can be promoted to int,long,float or double and so on.
If there are matching type arguments in the method, type promotion is not performed.
class Overloading2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
If there are no matching type arguments in the method, and each method promotes
similar number of arguments, there will be ambiguity.
class Overloading3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
The method must have the same parameter as in the parent class.
Output:
Bike is running safely
A real example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.
It is because the static method is bound with class whereas instance method is bound
with an object. Static belongs to the class area, and an instance belongs to the heap
area.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
class Animal{
void eat(){System.out.println("eating...");}
}
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();
}}
Output:
eating...
barking...
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();
}}
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there
is no super() or this().
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display(); }}