0% found this document useful (0 votes)
0 views42 pages

Unit20001 Obj in Java

In Java, an object is an entity with state, behavior, and identity, created from a class, which serves as a blueprint. A class can contain fields, methods, and constructors, and the 'new' keyword is used to allocate memory for objects. Constructors initialize objects and can be overloaded, while static variables and methods belong to the class rather than instances, optimizing memory usage.

Uploaded by

mohitmpatil7099
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views42 pages

Unit20001 Obj in Java

In Java, an object is an entity with state, behavior, and identity, created from a class, which serves as a blueprint. A class can contain fields, methods, and constructors, and the 'new' keyword is used to allocate memory for objects. Constructors initialize objects and can be overloaded, while static variables and methods belong to the class rather than instances, optimizing memory usage.

Uploaded by

mohitmpatil7099
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example
of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state.
It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
1. //Java Program to illustrate how to define a class and fields
2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null
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.

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.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

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.

Rule: If there is no constructor in a class, compiler automatically creates a


default constructor.

Rules for creating Java constructor


There are two rules defined for the 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

The default constructor is used to provide the default values to the object like
0, null, etc., depending on the type.
Example of default constructor
1. //Java Program to create and call a default constructor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }

Output:

Bike is created

Java 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.

Example of parameterized constructor

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }

Output:222 Aryan

111 Karan
222 Aryan

Constructor Overloading in Java


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.

1. //Java program to overload constructors


2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }

Output:

111 Karan 0
222 Aryan 25
Difference between constructor and method in
Java

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of an
object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you The method is not provided by the compiler in
don't have any constructor in a class. any case.

The constructor name must be same as the class The method name may or may not be same as the
name. 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

we are going to copy the values of one object into another using Java constructor.

1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}

16. public static void main(String args[]){


17. Student6 s1 = new Student6(111,"Karan");
18. Student6 s2 = new Student6(s1);
19. s1.display();
20. s2.display();
21. }
22. }

Output:

111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values
to another object. In this case, there is no need to create the constructor.

1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }

Output:

111 Karan
111 Karan

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.
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 class area at the time of class loading.
o Suppose there are 500 students in my college, now all instance data members
will get memory each time when the object is created. All students have its
unique rollno and name, so instance data member is good in such case. Here,
"college" refers to the common property of all objects. If we make it static, this
field will get the memory only once.

Java static property is shared to all objects.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
Test it Now

Output:

111 Karan ITS


222 Aryan ITS

2) Java 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.

Restrictions for the static method


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.

Example of static method

1. //Java Program to demonstrate the use of a static method.


2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }

Output:Compile Time Error

Why is the Java main method static?


It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem
of extra memory allocation.

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.

Example of static block

1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }

Output:static block is invoked


Hello main
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.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}

Output:

0 null 0.0
0 null 0.0

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}

Output:
111 ankit 5000.0
112 sumit 6000.0

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 the this keyword, compiler automatically adds this keyword while invoking the
method.

1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
14. hello n
hello n
hello m

3) this() : to invoke current class constructor

15. class A{
16. A(){System.out.println("hello a");}
17. A(int x){
18. this();
19. System.out.println(x);
20. }
21. }
22. class TestThis5{
23. public static void main(String args[]){
24. A a=new A(10);
25. }}

Output:

hello a
10
26.

4) this: to pass as an argument in the method


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:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
13. Output:
14. method is invoked

5) this: to pass as argument in the constructor call


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:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
21. Output:10
22. Output:10

Output:10

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive). Let's see the example:

1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }

Output:

Hello java
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?

Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors 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.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

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. We will learn about interfaces later.
Single Inheritance Example
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{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example


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.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Q) 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.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
14. Compile Time Error

Compile Time Error

Java Polymorphism

Method Overloading in Java


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.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.


Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the
method only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create
instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

Output:

22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the


return type of method only?
In java, method overloading is not possible by changing the return type of the
method only because of ambiguity. Let's see how ambiguity may occur:

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder


Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only. Let's see the simple example:

1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }

Output:

main with String[]

Method Overriding in Java

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.

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).
4. //Java Program to illustrate the use of Java Method Overriding
5. //Creating a parent class.
6. class Vehicle{
7. //defining a method
8. void run(){System.out.println("Vehicle is running");}
9. }
10. //Creating a child class
11. class Bike2 extends Vehicle{
12. //defining the same method as in the parent class
13. void run(){System.out.println("Bike is running safely");}
14.
15. public static void main(String args[]){
16. Bike2 obj = new Bike2();//creating object
17. obj.run();//calling method
18. }
19. }

Output:

Bike is running safely

1. //Java Program to demonstrate the real scenario of Java Method Overriding


2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime
polymorphism, so we will learn it later.

Why can we not override static method?


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.

Can we override java main method?


No, because the main is a static method.
Difference between method overloading
and method overriding in java
There are many differences between method overloading and method overriding in
java. A list of differences between method overloading and method overriding are
given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already
provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two classes that have
IS-A (inheritance) relationship.

3) In case of method overloading, parameter must In case of method overriding, parameter must be
be different. same.

4) Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.

5) In java, method overloading can't be performed Return type must be same or covariant in method
by changing return type of the method overriding.
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class


instance variable.
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
16. black
17. white
Output:

Black

White
2) 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.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
17. ...

Output:

eating...
barking...

3) super is used to invoke parent class


constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}

Output:

animal is created
dog is created
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}

Output:
1 ankit 45000

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction

. There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java
.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signature, no body, see: Java abstract method). Also, the variables declared in an interface
are public, static & final by default.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

class implements interface but an interface extends another interface.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

Output:
ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in


java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in the case of class
because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the
implementation class.

Abstract Class Interface

An abstract class can extend only one An interface can extend any number of
1
class or one abstract class at a time interfaces at a time

An abstract class can extend another An interface can only extend another
2
concrete (regular) class or abstract class interface

An abstract class can have both abstract An interface can have only abstract
3
and concrete methods methods

In abstract class keyword “abstract” is


In an interface keyword “abstract” is
4 mandatory to declare a method as an
optional to declare a method as an abstract
abstract

An abstract class can have protected An interface can have only have public
5
and public abstract methods abstract methods
An abstract class can have static, final
interface can only have public static final
6 or static final variable with any access
(constant) variable
specifier

Interface inheritance
A class implements an interface, but one interface extends another interface.

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }

Output:

Hello
Welcome

Static Method in Interface


1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}

Output:

drawing rectangle
27

Constructor in Java
• An Interface in Java doesn't have a constructor because all data
members in interfaces are public static final by default, they are
constants (assign the values at the time of declaration).
• There are no data members in an interface to initialize them through the
constructor.
• In order to call a method, we need an object, since the methods in the
interface don’t have a body there is no need for calling the methods in an
interface.
• Since we cannot call the methods in the interface, there is no need of
creating an object for an interface and there is no need of having a
constructor in it.
// Java program that demonstrates why
// interface can not have a constructor
// Creating an interface
interface Subtraction {
// Creating a method, by default
// this is a abstract method
int subtract(int a, int b);
}
// Creating a class that implements
// the Subtraction interface
class ConstructorWithInterface implements Subtraction {
// Defining subtract method
public int subtract(int a, int b)
{
int k = a - b;
return k;
}

// Driver Code
public static void main(String[] args)
{

// Creating an instance of
// ConstructorWithInterface class
ConstructorWithInterface g = new ConstructorWithInterface ();
System.out.println(g.subtract(20, 5));
}
}

Overloading methods of an interface


import java.util.Scanner;
interface MyInterface{
public void display();
public void display(String name, int age);
}
public class OverloadingInterfaces implements MyInterface{
String name;
int age;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void display(String name, int age) {
System.out.println("Name: "+name);
System.out.println("Age: "+age);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
OverloadingInterfaces obj = new OverloadingInterfaces();
obj.display();
obj.display(name, age);
}
}

Output
Enter your name:
Krishna
Enter your age:
25
This is the implementation of the display method
Name: Krishna
Age: 25

You might also like