0% found this document useful (0 votes)
17 views

Ch3 Objects Classes

Uploaded by

andyurus1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Ch3 Objects Classes

Uploaded by

andyurus1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Bhagwan Mahavir University

Unit 3: Objects and classes in Java


3.1 Creating Classes and objects
3.2 Memory allocation for objects.
3.3 Methods, Constructor & Overloading
3.4 Implementation of Inheritance
3.5 this & super keyword – Method overriding
3.6 Static members, static block, static class
3.7 Abstract classes and methods
3.8 Implementation of Polymorphism
3.9 Nested and Inner classes
3.10 Interfaces
Interface Declaration,
Inheriting and Hiding Concepts,
Overloading and Overriding Methods,
Interfaces implementation

3.1 Creating Classes and objects

Java Classes
 Java is an object-oriented programming language.
 Everything in Java is associated with classes and objects, along with its
attributes and methods.
 For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.

Ex. student.java
Create a class named "student" with a variable x:

class student
{
int rno=101;
String name=”Tanay”;
}

Java Programming Page 1


Bhagwan Mahavir University

Create an Object

In Java, an object is created from a class. We have already created the class
named student, so now we can use this to create objects.

To create an object of student, specify the class name, followed by the object
name, and use the keyword new:

Example
Create an object called "s1" and print the value of rno and name:

public class student {

int rno = 101;

String name=”Tanay”;
public static void main(String[] args) {
student s1 = new student(); // s1 is an object of class student
System.out.println(s1.rno); //101
System.out.println(s1.name); //Tanay

}}

Multiple Objects

You can create multiple objects of one class:

public class student {


int rno = 101;

String name=”Tanay”;

public static void main(String[] args) {

student s1 = new student(); // s1 is an object of class student


student s2 = new student();
System.out.println(s1.rno); //101
System.out.println(s1.name); //Tanay
System.out.println(s2.rno); //101
System.out.println(s2.name);//Tanay

}}
Java Programming Page 2
Bhagwan Mahavir University

3.2 Memory allocation for object / How are Java objects stored in memory?

In Java, all objects are dynamically allocated on Heap.

This is different from C++ where objects can be allocated memory either on Stack
or on Heap.

In C++, when we allocate the object using new(), the object is allocated on Heap,
otherwise on Stack if not global or static.
In Java, when we only declare a variable of a class type, only a reference is created
(memory is not allocated for the object).

To allocate memory to an object, we must use new(). So the object is always


allocated memory on heap.

For example, following program fails in the compilation. Compiler gives error
“Error here because t is not initialized”.

class Test {

// class contents

void show()

System.out.println("Test::show() called");

public class student {

public static void main(String[] args)

Test t;

t.show(); // Error here because t is not initialized

}}

Allocating memory using new() makes above program work.

Java Programming Page 3


Bhagwan Mahavir University

class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
Test t = new Test(); // all objects are dynamically allocated
t.show(); // No error
}
}

Method in Java

In general, a method is a way to perform some task.

Similarly, the method in Java is a collection of instructions that performs a


specific task.

It provides the reusability of code.

We can also easily modify code using methods.

A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation.

We do not require to write code again and again.

It also provides the easy modification and readability of code, just by adding or
removing a chunk of code.

The method is executed only when we call or invoke it.

The most important method in Java is the main() method.

Java Programming Page 4


Bhagwan Mahavir University

Method Declaration

The method declaration provides information about method attributes, such as


visibility, return-type, name, and arguments.

It has six components that are known as method header, as we have shown in the
following figure.

Method Signature: Every method has a method signature. It is a part of the


method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

 Public: The method is accessible by all classes when we use public specifier
in our application.
 Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
 Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.

Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.

Java Programming Page 5


Bhagwan Mahavir University

Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must be
subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in


the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.

4 ways to Access and Create a methods:

1. Not passing not returning OR no argument no returning


Example:
import java.util.*;
class addition
{
int a,b;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter A:");
a=sc.nextInt();
System.out.println("Enter B:");
b=sc.nextInt();
}
void display()
{
System.out.println("A is:"+a);
System.out.println("B is:"+b);
System.out.println("Addition of "+a+" and "+b+" is:"+(a+b));
}
public static void main(String s[])
{
addition s1=new addition();
s1.getdata();
s1.display();
}
}

Java Programming Page 6


Bhagwan Mahavir University

2. No argument and returning


Example:
import java.util.*;
class addition
{
int a,b;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter A:");
a=sc.nextInt();
System.out.println("Enter B:");
b=sc.nextInt();
}
int display()
{
System.out.println("A is:"+a);
System.out.println("B is:"+b);
return a+b;
}
public static void main(String s[]) {
addition s1=new addition();
s1.getdata();
int c=s1.display();
System.out.println("Addition is:"+c);
}
}

Java Programming Page 7


Bhagwan Mahavir University

3. Passing something & no Returning OR Argument and no returning


import java.util.*;
class addition
{
int a,b;
void getdata(int a1, int b1)
{
a=a1;
b=b1;
}
void display()
{
System.out.println("A is:"+a);
System.out.println("B is:"+b);
System.out.println("Addition of "+a+" and "+b+" is:"+(a+b));
}
public static void main(String s[])
{
addition s1=new addition();
Scanner sc=new Scanner(System.in);
System.out.println("Enter A:");
int a=sc.nextInt();
System.out.println("Enter B:");
int b=sc.nextInt();
s1.getdata(a,b);
s1.display();
}
}

Java Programming Page 8


Bhagwan Mahavir University

4. Passing Something & returning


Example:
import java.util.*;
class addition
{
int a,b;
void getdata(int a1, int b1)
{
a=a1;
b=b1;
}
int display()
{
System.out.println("A is:"+a);
System.out.println("B is:"+b);
return a+b;
}
public static void main(String s[]) {
addition s1=new addition();
Scanner sc=new Scanner(System.in);
System.out.println("Enter A:");
int a=sc.nextInt();
System.out.println("Enter B:");
int b=sc.nextInt();
s1.getdata(a,b);
int c=s1.display();
System.out.println("Addition of "+a+" and "+b+" is:"+c);
}}

Java Programming Page 9


Bhagwan Mahavir University

3.1 Method Overloading

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 Overload`ing: 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.

Example:

class Adder{
int add(int a,int b){
return a+b;
}

Java Programming Page 10


Bhagwan Mahavir University

int add(int a,int b,int c)


{
return a+b+c;
} }

class addition{
public static void main(String[] args){
Adder a1=new Adder();
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

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.

class Adder{
int add(int a, int b){
return a+b;
}
double add(double a, double b){
return a+b;
} }
class TestOverloading2{
public static void main(String[] args){
Adder a1=new Adder();
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Java Programming Page 11
Bhagwan Mahavir University

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:

class Adder
{
int add(int a,int b)
{
return a+b;
}

double add(int a,int b)


{
return a+b;
}
}
class TestOverloading3{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));//ambiguity
}
}

Output:

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

System.out.println(Adder.add(11,11)); //Here, how can java determine which


sum() method should be called?

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.

Java Programming Page 12


Bhagwan Mahavir University

Let's see the simple example:

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

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.

Java Programming Page 13


Bhagwan Mahavir University

There are three types of constructors in Java:

1. No-arg (Default) constructor


2. Parameterized constructor.
3. Copy 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.

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
4. Constructor is automatically called when object is created.

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.

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>()
{
//Statements
}

Java Programming Page 14


Bhagwan Mahavir University

Example of default constructor


In this example, we are creating the no-arg constructor in the Addition class.

It will be invoked at the time of object creation.

class Addition
{
Addition() //creating a default constructor
{
System.out.println("Addition is created");
}
public static void main(String args[]){
Addition a1=new Addition();//calling a default constructor
}
}

Output:

Addition is created.

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


constructor.

(Q) What is the purpose of a default 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 that displays the default values

class Student
{
int id;
String name;

void display()
{
System.out.println(id+" "+name);
}

Java Programming Page 15


Bhagwan Mahavir University

public static void main(String args[]){


Student s1=new Student();
Student s2=new Student();
//displaying values of the object
s1.display();
s2.display();
} }

Output:

0 null
0 null

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.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized


constructor.

Why use the 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

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.

class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n) {
id = i;
name = n;
}
Java Programming Page 16
Bhagwan Mahavir University

//method to display the values


void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
} }

Output:

111 Karan
222 Aryan

Copy Constructor

In Java, a copy constructor is a special type of constructor that creates an object


using another object of the same Java class. It returns a duplicate copy of an
existing object of the class.

Example:

class student

int id;

String name;

student(int i,String n) { //parameterize constructor

id=i;

name=n;

Java Programming Page 17


Bhagwan Mahavir University

student(student s) { //copy constructor

id=s.id;

name=s.name;

void display() {

System.out.println(id+" "+name);

public static void main(String s[]){

student s1=new student(101,"Tanay");

student s2=new student(s1);

s1.display();

s2.display();

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.

Example of Constructor Overloading

class student {

int id;

String name;

Java Programming Page 18


Bhagwan Mahavir University

student() // Default Constructor

System.out.println("It's a Default constructor");

student(int i,String n) { //Parameterized constructor

id=i;

name=n;

student(student s) {

id=s.id;

name=s.name;

void display() {

System.out.println(id+" "+name);

public static void main(String s[])

student s1=new student(101,"Tanay");

student s2=new student(s1);

s1.display();

s2.display();

}}

Java Programming Page 19


Bhagwan Mahavir University

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method

A constructor is used to initialize the state A method is used to expose the behavior
of an object. 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 The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

The constructor name must be same as the The method name may or may not be
class name. same as the class name.

3.4 Implementation of Inheritance

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


 For Method Overriding(so runtime polymorphism can be achieved).
 For Code Reusability.

Java Programming Page 20


Bhagwan Mahavir University

Terms used in Inheritance

 Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.

The syntax of Java Inheritance

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.

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.

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.

Java Programming Page 21


Bhagwan Mahavir University

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Java Programming Page 22


Bhagwan Mahavir University

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance.

Example:

import java.util.*;

class student{

int sid;

String sname;

void getdata() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter SId:");

sid=sc.nextInt();

System.out.println("Enter Sname:");

sname=sc.next();

void putdata() {

System.out.println("SId is:"+sid);

System.out.println("Sname is:"+sname);

}}

class teacher extends student{

int tid;

String tname;

void get() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter TId:");
Java Programming Page 23
Bhagwan Mahavir University

tid=sc.nextInt();

System.out.println("Enter Tname:");

tname=sc.next();

void put() {

System.out.println("TId is:"+tid);

System.out.println("Tname is:"+tname);

}}

class inheritance{

public static void main(String s[]) {

teacher t1=new teacher();

t1.getdata(); t1.put();

t1.get(); }}

t1.putdata();

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, principal class inherits the teacher class which
again inherits the student class, so there is a multilevel inheritance.

Example:

import java.util.*;

class student

int sid;

String sname;

Java Programming Page 24


Bhagwan Mahavir University

void getdata()

Scanner sc=new Scanner(System.in);

System.out.println("Enter SId:");

sid=sc.nextInt();

System.out.println("Enter Sname:");

sname=sc.next();

void putdata()

System.out.println("========================");

System.out.println("SId is:"+sid);

System.out.println("Sname is:"+sname);

class teacher extends student{

int tid;

String tname;

void get() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter TId:");

tid=sc.nextInt();
Java Programming Page 25
Bhagwan Mahavir University

System.out.println("Enter Tname:");

tname=sc.next();

void put() {

System.out.println("TId is:"+tid);

System.out.println("Tname is:"+tname);

}}

class principal extends teacher{

int pid;

String pname;

void getp() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter PId:");

pid=sc.nextInt();

System.out.println("Enter Pname:");

pname=sc.next();

void putp() {

System.out.println("PId is:"+pid);

System.out.println("Pname is:"+pname);

System.out.println("========================");

}}
Java Programming Page 26
Bhagwan Mahavir University

class multilevel{

public static void main(String s[]) {

principal p1=new principal ();

p1.getdata();

p1.get();

p1.getp();

p1.putdata();

p1.put();

p1.putp();

}}

Hierarchical Inheritance Example

When two or more classes inherit a single class, it is known as hierarchical


inheritance. In the example given below, teacher and principal classes inherits the
student class, so there is hierarchical inheritance.

Example:

import java.util.*;

class student{

int sid;

String sname;

void getdata() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter SId:");

Java Programming Page 27


Bhagwan Mahavir University

sid=sc.nextInt();

System.out.println("Enter Sname:");

sname=sc.next();

void putdata() {

System.out.println("========================");

System.out.println("SId is:"+sid);

System.out.println("Sname is:"+sname);

}}

class teacher extends student{

int tid;

String tname;

void get() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter TId:");

tid=sc.nextInt();

System.out.println("Enter Tname:");

tname=sc.next();

void put() {

System.out.println("TId is:"+tid);

System.out.println("Tname is:"+tname); }}
Java Programming Page 28
Bhagwan Mahavir University

class principal extends student{

int pid;

String pname;

void getp() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter PId:");

pid=sc.nextInt();

System.out.println("Enter Pname:");

pname=sc.next(); }

void putp() {

System.out.println("PId is:"+pid);

System.out.println("Pname is:"+pname);

System.out.println("========================");

}}

class hirarchical{

public static

void main(String s[]) {

principal p1=new principal ();

p1.getdata();

p1.getp();

p1.putdata();

p1.putp();
Java Programming Page 29
Bhagwan Mahavir University

teacher t1=new teacher();

t1.getdata();

t1.getp();

t1.putdata();

t1.putp(); }}

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(super)
class.

Example:

import java.util.*;
class student
{
int sid;
String sname;

Java Programming Page 30


Bhagwan Mahavir University

void getdata()
{
sname="BMU";
}
void putdata()
{
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
}}

class teacher extends student


{
int tid;
String tname;
void get()
{
super.sid=101; //assign value to data member of super class using super
keyword
tid=201;
tname="DKP";
}
void put()
{
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname);

Java Programming Page 31


Bhagwan Mahavir University

System.out.println("Sname is:"+super.sname); //super keyword access data


member of super class
}}
class super1
{
public static void main(String s[])
{
teacher t1=new teacher();
t1.getdata();
t1.get();
t1.putdata();
t1.put(); }}

(2) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.
Example:

class student{

int sid;

String sname;

student() {

sid=101;

sname="BMU";

Java Programming Page 32


Bhagwan Mahavir University

void putdata() {

System.out.println("SId is:"+sid);

System.out.println("Sname is:"+sname);

}}

class teacher extends student{

int tid;

String tname;

teacher() {

super(); //call super class constructor

tid=201;

tname="DKP"; }

void put() {

System.out.println("TId is:"+tid);

System.out.println("Tname is:"+tname); }}

class super2{

public static void main(String s[]) {

teacher t1=new teacher(); //call constructor of child class(teacher)

t1.putdata();

t1.put(); }

Java Programming Page 33


Bhagwan Mahavir University

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

Example:

class student

int sid;

String sname;

student() {

sid=101;

sname="BMU";

void putdata() {

System.out.println("SId is:"+sid);

System.out.println("Sname is:"+sname);

class teacher extends student{

int tid;

String tname;

Java Programming Page 34


Bhagwan Mahavir University

teacher() {

super(); //call super class constructor

tid=201;

tname="DKP";

void put() {

super.putdata(); // call super class putdata()

System.out.println("TId is:"+tid);

System.out.println("Tname is:"+tname);

}}

class super3{

public static void main(String s[]) {

teacher t1=new teacher();

t1.put(); }

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.

Java Programming Page 35


Bhagwan Mahavir University

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
 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).

Example:
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}

class Child extends Parent {

void show()
{
System.out.println("Child's show()");
}
}

class Main {
public static void main(String[] args)
{

Parent obj1 = new Parent();


obj1.show(); //call Parent class show method
Child obj2 = new Child();
obj2.show();//call Child class show method
}}
Output:
Parent's show()
Child's show()
Java Programming Page 36
Bhagwan Mahavir University

Method Overriding using super keyword:


Example :
class Parent {
void show()
{
System.out.println("Parent's show()");
}}

class Child extends Parent {

void show()
{
super.show(); // call parent class show()
System.out.println("Child's show()");
}}

class Main {
public static void main(String[] args)
{

Child obj1 = new Child();


obj1.show();//call Child class show method
}}
Output:
Parent's show()
Child's show()

Difference between method overloading and method overriding in java

No. Method Overloading Method Overriding

Method overriding is used to provide


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

(2) Method overloading is performed Method overriding occurs in two

Java Programming Page 37


Bhagwan Mahavir University

within class. classes that have IS-A (inheritance)


relationship.

In case of method overloading, In case of method overriding,


(3)
parameter must be different. parameter must be same.

Method overloading is the example of Method overriding is the example of


(4)
compile time polymorphism. run time polymorphism.

In java, method overloading can't be


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

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

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

Java Programming Page 38


Bhagwan Mahavir University

Example:

class student

int rno;

String name,grade;

void getdata(int rno,String name,String grade) {

this.rno=rno;

this.name=name;

this.grade=grade;

void putdata() {

System.out.println("Roll No:"+rno);

System.out.println("Name:"+name);

System.out.println("Grade:"+grade);

}}

class this_ex1{

public static void main(String s[]) {

student s1=new student();

s1.getdata(101,"DKP","A+");

s1.putdata();

}}
Java Programming Page 39
Bhagwan Mahavir University

(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. Let's see the example

Example:
class student{
int rno;
String name,grade;

void greeting() {
System.out.println("Hello, Guys Welcome to Java World");
}
void getdata(int rno,String name,String grade) {
this.rno=rno;
this.name=name;
this.grade=grade;
}
void putdata() {
this.greeting();
System.out.println("Roll No:"+rno);
System.out.println("Name:"+name);
System.out.println("Grade:"+grade);
}}

Java Programming Page 40


Bhagwan Mahavir University

class this_ex2{
public static void main(String s[]) {
student s1=new student();
s1.getdata(101,"DKP","A+");
s1.putdata();
}}

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

Calling default constructor from parameterized constructor:

class student{

student(){

System.out.println("Hello class student. I am Default Constructor"); }

student(int x)

this(); // call default constructor

System.out.println(x);

}}

class this_ex3{

public static void main(String args[]){

student s1=new student(101);

}}

Java Programming Page 41


Bhagwan Mahavir University

Calling parameterized constructor from default constructor:


class student{
student()
{
this(101); // call parameterize constructor
System.out.println("Hello class student. I am Default Constructor");
}
student(int x)
{
System.out.println(x);
}}
class this_ex3{
public static void main(String args[])
{
student s1=new student();
}}

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.

Example:
class Student {
int rollno;
String name,grade;
float fee;
Java Programming Page 42
Bhagwan Mahavir University

Student(int rollno,String name,String grade){


this.rollno=rollno;
this.name=name;
this.grade=grade;
}
Student(int rollno,String name,String grade,float fee){
this(rollno,name,grade);//reusing constructor
this.fee=fee;
}
void display() {
System.out.println(rollno+" "+name+" "+grade+" "+fee);
}}
class this_ex4
{
public static void main(String args[]){
Student s2=new Student(112,"KSP","java",6000);
s2.display();
}}

Java Programming Page 43


Bhagwan Mahavir University

Difference between super() and this() in java Program

Sr.
Key This super
No.

Represent On other hand super keyword


this keyword mainly represents
1 and represents the current instance of a
the current instance of a class.
Reference parent class.

Interaction
this keyword used to call default super keyword used to call default
2 with class
constructor of the same class. constructor of the parent class.
constructor

this keyword used to access


Method One can access the method of parent
3 methods of the current class as it
accessibility class with the help of super keyword.
has reference of current class.

this keyword can be referred


On other hand super keyword can't
from static context i.e can be
be referred from static context i.e
invoked from static instance. For
Static can't be invoked from static instance.
4 instance we can write
context For instance we cannot write
System.out.println(this.x) which
System.out.println(super.x) this will
will print value of x without any
leads to compile time error.
compilation or runtime error.

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.

Java Programming Page 44


Bhagwan Mahavir University

The static can be:

1. Variable (also known as a class variable)


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

(1) Java static variable

If you declare any variable as static, it is known as a static variable.

 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.
 The static variable gets memory only once in the class area at the time of
class loading.

Advantages of static variable

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

Program of the counter without static variable

class Counter
{
int count=0; //will get memory each time when the instance is created

Counter()
{
count++; //incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Java Programming Page 45


Bhagwan Mahavir University

Output:
1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.

class Counter
{
static int count=0; //will get memory each time when the instance is created

Counter()
{
count++; //incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
2
3
(2) Java static method

If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Java Programming Page 46


Bhagwan Mahavir University

Example of static method

class Student
{
int r;
String name;
static String college = "GTU";
static void change() //static method {
college = "BMU";
}
Student(int r, String name)
{
this.r = r;
this.name = name; }

void display()
{
System.out.println(r+" "+name+" "+college);
}
}
public class static_ex
{
public static void main(String args[])
{
System.out.println(Student.college);
Student.change();
Student s1 = new Student(111,"Tanay");
s1.display();
}
}
Output:
GTU
111 Tanay BMU

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Java Programming Page 47
Bhagwan Mahavir University

(3) Java static block

 It is a set of statements, which will be executed by the JVM before execution of


main method.
 At the time of class loading if we want to perform any activity we have to define
that activity inside static block because static block execute at the time of class
loading.
 In a class we can take any number of static block but all these static block will be
execute from top to bottom.

Example of static block

class demo{

static
{
System.out.println("static_1 block is invoked");
}
static
{
System.out.println("static _2 block is invoked");

public static void main(String args[]){

System.out.println("Hello main");

}}

Output:
static_1 block is invoked
static_2 block is invoked
Hello main
(4) Java Static Class

We can declare a class static by using the static keyword. A class can be declared static
only if it is a nested class. It does not require any reference of the outer class. The
property of the static class is that it does not allows us to access the non-static members
of the outer class.

Java Programming Page 48


Bhagwan Mahavir University

To understand the concept of static class first we need to understand the concept of inner,
outer, and nested class.

Inner class

The classes that are non-static and nested are called inner classes

Outer Class

The class in which nested class is defined is called outer class.

Nested Class

Java allows us to define a class within a class that is known as a nested class.

It may be static or non-static. The major difference between static and non-static class is
that:

 An instance of the static nested class can be created without creating an instance of
its outer class.
 The static and non-static members of an outer class can be accessed by an inner
class.
 The static members of the outer class can be accessed only by the static class.

Example:

class student {

static String name= "SYBCA";

static class Nested_student //Static and nested class

public void show() //non-static method of the nested class

System.out.println(name);

name="Tanay"; } }}

Java Programming Page 49


Bhagwan Mahavir University

class static_class

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

student.Nested_student s1=new student.Nested_student();

s1.show();

System.out.println(student.name);

} }

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java

It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Java Programming Page 50


Bhagwan Mahavir University

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.

Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of
the method.

Example of abstract class

abstract class A{}

Example:

abstract class student1{

abstract void result();}

class student2 extends student1{

void result() {

System.out.println("It's My result");

}}

class abstract_ex{

public static void main(String s[]) {

student2 s1=new student2();

s1.result();

} }

Java Programming Page 51


Bhagwan Mahavir University

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.

Example:

abstract class salary{

int basic,da;

salary(int basic,int da) {

this.basic=basic;

this.da=da; }

void greetings() {

System.out.println("Hello, Good morning all. I am Abstract Class"); }

abstract void ComputeSalary();}

class GSalary extends salary

int hra;

GSalary(int basic,int da,int hra) {

super(basic,da);

this.hra=hra;

void ComputeSalary() {

System.out.println("Gross Salary:"+(basic+da+hra));

}}

Java Programming Page 52


Bhagwan Mahavir University

class abstract_ex1{

public static void main(String s[]) {

GSalary sal=new GSalary(25000,1000,2500);

sal.greetings();

sal.ComputeSalary();

}}

Output:

Hello, Good morning all. I am Abstract Class

Gross Salary:28500

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
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.

It cannot be instantiated just like the abstract class

Uses of Java interface


There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling. (Loose coupling in Java means that the
classes are independent of each other)

Java Programming Page 53


Bhagwan Mahavir University

Declaring 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:
interface interface_name
{
// declare constant fields
// declare methods that abstract
// by default.
}
Relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Example

interface A
{
void display();
}

Java Programming Page 54


Bhagwan Mahavir University

class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class Interface_ex
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}

Interface Implements in multiple Class


Example:
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello B");
}

Java Programming Page 55


Bhagwan Mahavir University

}
class C implements A
{
public void display()
{
System.out.println("Hello C");
}
}
class MB
{
public static void main(String args[]){
B obj1 = new B();
obj1.display();
C obj2 = new C();
obj2.display();
}}

Multiple methods in Interface:

Example:

interface A

void greeting1();

void greeting2();

Java Programming Page 56


Bhagwan Mahavir University

class B implements A

public void greeting1()

System.out.println("Good morning B");

public void greeting2()

System.out.println("Have a Nice Day B");

}}

class MB{

public static void main(String args[]){

B obj1 = new B();

obj1.greeting1();

obj1.greeting2();

}}

Multiple inheritance by interface


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

Java Programming Page 57


Bhagwan Mahavir University

Example:
interface A{
void display();
}

interface B{
void show();
}

class C implements A,B


{
public void display() {
System.out.println("Display method");
}
public void show(){
System.out.println("show method");
}}

class MB{
public static void main(String args[]){
C obj = new C();
obj.display();
obj.show(); }}
Output:
Hello
Welcome
Java Programming Page 58
Bhagwan Mahavir University

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

Example:
interface A
{
void display();
}
interface B extends A //one interface extends another interface
{
void show();
}
class C implements B // one class implements another interface
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class MB
{
public static void main(String args[])
{
C obj = new C(); obj.display(); obj.show();
}}

Java Programming Page 59


Bhagwan Mahavir University

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
(1) Abstract class can have abstract and non-
Interface can have only abstract methods.
abstract methods.
(2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
(3) Abstract class can have final, non-final, static
Interface has only static and final variables.
and non-static variables.
(4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
(5) The abstract keyword is used to declare
The interface keyword is used to declare interface.
abstract class.
(6) An abstract class can extend another Java class
An interface can extend another Java interface only.
and implement multiple Java interfaces.
(7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
(8) A Java abstract class can have class members
Members of a Java interface are public by default.
like private, protected, etc.
(9) Example: Example:
public abstract class student public interface A
{ {
public abstract void result(); void display();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Java Programming Page 60


Bhagwan Mahavir University

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.

The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:

compile-time polymorphism

runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism.

Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:

class A{}

class B extends A{}

A a=new B();//upcasting

Java Programming Page 61


Bhagwan Mahavir University

Example:

class student
{
void result()
{
System.out.println("Result from student class");
}
}

class Boy extends student


{
void result()
{
System.out.println("Result from Boy class");
}
}

class Girl extends student


{
void result()
{
System.out.println("Result from Girl class");
}
}

class poly_ex
{
public static void main(String s[])
{
student s1;
Girl g1=new Girl();
Boy b1=new Boy();
s1=g1;
s1.result();
s1=b1;
s1.result();
}
}
Output:
Result from Girl class
Result from Boy class

Java Programming Page 62


Bhagwan Mahavir University

Java Inner Classes (Nested Classes)

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data
members and methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
} }
Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can access all
the members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class


Sometimes users need to program a class in such a way so that no other class can access
it. Therefore, it would be better if you include it within other classes.

Example:

class result { {
private double per=82.61; public static void main(String args[])
class student { {
void marksheet() result r1=new result();
{ result.student s1=r1.new student();
System.out.println("Percentage is "+per); s1.marksheet();
} }} } }
class inner_class
Java Programming Page 63

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy