Java Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Objects and Classes in Java

An object in Java is the physical as well as a logical entity


A class in Java is a logical entity only.

Object in Java
An entity that has state and behaviour 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:


State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user.
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.

Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behaviour.
The object is an instance of a class.

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:


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

class <class_name>
{
field;
method;
}

Instance variable in Java


A variable which is created inside the class but outside the method is known as an instance
variable.
Instance variable doesn't get memory at compile time.
It gets memory at runtime when an object or instance is created.

Method in Java
In Java, a method is like a function which is used to expose the behaviour of an object.

Advantage of Method
Code Reusability
Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime.
All objects get memory in Heap memory area.

Object and Class Example: main within the class


In this example,
we have created a Student class which has two data members’ id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
we are creating a main() method inside the class.

//Defining a Student class.


class Student{
//defining fields
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: main outside the class

In real time development, we create classes and use it from another class.
It is a better approach than previous one.

where we are having main() method in another class.


We can have multiple classes in different Java files or single Java file.
If you define multiple classes in a single Java source file,
it is a good idea to save the file name with the class name which has main() method.

// the main method in another class


//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

3 Ways to initialize object


1. By reference variable
2. By method
3. By constructor

Example 1: Initialization through reference

Initializing an object means storing data into the object.


where we are going to initialize the object through a reference variable.

class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name); //printing members with a white space
} }
Example 2: create multiple objects and store information in it through reference variable.

class Student
{
int id;
String name;
}
class TestStudent3{
public static void main(String args[])
{
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}

2) Object and Class Example: Initialization through method

we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method.
we are displaying the state (data) of the objects by invoking the displayInformation() method.

class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation(); } }
Object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area.
s1 and s2 both are reference variables that refer to the objects allocated in memory.

Example1:

class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s)
{
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Example 2:

class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Real World Example 3: Account

//Java Program to demonstrate the working of a banking-system


//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw() methods

class Account
{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println("Insufficient Balance");
}
Else
{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args)
{
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}

Constructors
 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.
 Java compiler provides a default constructor by default.

Rules for creating Java constructor


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
1. Default constructor (no-arg constructor)
2. 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

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{}

Example1 of default constructor


//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
Class test{
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Explanation:
In this example, we are creating the no-arg constructor in the Bike class.
It will be invoked at the time of object creation
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.

Example2 of default constructor that displays the default values


//Let us see another example of default constructor which displays the default values
Class
Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation:
We 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.

Example1 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.
//Java Program to demonstrate the use of the parameterized constructor
.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
class test{
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
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.

Example1 of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
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:
1. By constructor
2. By assigning the values of one object into another
3. By clone() method of Object class

Example1, we are going to copy the values of one object into another using Java
constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
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.

class Student7{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:
111 Karan
111 Karan

Static keyword in Java


 It is used for memory management mainly.
 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.
 The static variable can be used to refer to the common property of all objects (which
is not unique for each object),
 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.
Restrictions for the static method
There are two main restrictions for the static method.
They are:
1. The static method cannot use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
Advantages of static variable
 It makes your program memory efficient (i.e., it saves memory).

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno; //instance variable
String name;
static String college ="ITS"; //static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display ()
{System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}

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

Example1 of static method


class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change(); //calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Example2 of static method


//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}

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


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.

 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.
*if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
Explanation:
 parameters (formal arguments) and instance variables are same.
 this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit 5000.0
112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:

2) this: to invoke current class method


 invoke the method of the current class by using the this keyword.
 If you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.

class A
{ void m(){System.out.println("hello m");}
void n()
{ System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

Output:
hello n
hello m

3) this() : to invoke current class constructor


 The this() constructor call can be used to invoke the current class constructor.
 It is used to reuse the constructor.
 it is used for constructor chaining.

Calling default constructor from parameterized constructor:


class A{
A(){System.out.println("hello a");}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}

Output:
hello a
10

Calling parameterized constructor from default constructor:


class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Output:
5
hello a

this() constructor call


Rule: Call to this() must be the first statement in constructor.
 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.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit java 0.0
112 sumit java 6000.0

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.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

Output:
method is invoked

Application of this that can be passed as an argument:


In event handling have to provide reference of a class to another one.
It is used to reuse one object in many methods.

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


 can pass the this keyword in the constructor also.
 useful if we have to use one object in multiple classes.
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data); //using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

Output:10

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


 return this keyword as an statement from the method.
 return type of the method must be the class type (non-primitive).

Syntax of this that can be returned as a statement


return_type method_name()
{
return this;
}

Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:
Hello java

In this program, we are printing the reference variable and this, output of both variables
are same.
 this keyword refers to the current class instance variable.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}

Output:
A5@22b3ea59
A5@22b3ea59

Java Inner Classes


 In Java, it is also possible to nest classes (a class within a class).
 The purpose of nested classes is to group classes that belong together,
which makes your code more readable and maintainable.
 To access the inner class, create an object of the outer class, and then
create an object of the inner class:
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}

class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}}
// Outputs 15 (5 + 10)

Modification: to implement arithmetic operations using nested classes


class OuterClass {
int x = 10;
class InnerClass {
int y = 15;
}}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
System.out.println(myInner.y - myOuter.x);
System.out.println(myInner.y * myOuter.x);
System.out.println(myInner.y / myOuter.x);
System.out.println(myInner.y % myOuter.x);

}}

Another Example of nested classes:


Write a program to print area of the square, rectangle and circle using nested
classes

Static Inner Class


An inner class can also be static, which means that you can access it without
creating an object of the outer class:
Example
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}
}

// Output
5

Inheritance in Java
 It 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).
 Inheritance in Java is that you can create new classes that are built upon
existing classes.
 It inherits from an existing class
 can reuse methods and fields of the parent class.
 can add new methods and fields in the current class also.
 Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

Why use inheritance in java

1. For Method Overriding (runtime polymorphism can be achieved).


2. For Code Reusability.

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:

 It is a mechanism to reuse the fields and methods of the existing class


when create a new class.
 can use the same fields and methods already defined in the previous
class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
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.
a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.

Java Inheritance Example 1:

Programmer is the subclass and Employee is the superclass.


The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;

public static void main(String args[]){


Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

Explanation:
In this example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.

Types of inheritance in java


Three types of inheritance in java:

1. single,
2. multilevel
3. and hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only.

Single Inheritance Example 1:

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

 Dog class inherits the Animal class, so there is the single inheritance.

class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance.


BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog
{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example

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


inheritance.

 Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Final Keyword In Java


1. Final variable
2. Final method
3. Final class
 The final keyword can be applied with the variables,
 A final variable that have no value it is called blank final variable or
uninitialized final variable.
 It can be initialized in the constructor only.
 The blank final variable can be static also which will be initialized in the
static block only.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable
(It will be constant).

Example1 of final variable


There is a final variable speedlimit,
The value of the final variable speedlimit, can't be changed because final variable
once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:
Compile Time Error

2) Java final method


If you make any method as final, It cannot override it.

class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

final class Bike{}


class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile Time Error

Classes and Methods


Data abstraction is the process of hiding certain details and showing only essential information
to the user.
Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class:
It is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
Abstract method:
It can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
 An abstract class can have both abstract and regular methods
Example1 Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal
{
public void animalSound()
{
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Java Interface
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty
bodies:
Syntax of interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class.
// Example1 Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
It can be achieved with interfaces, because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma
Example1
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

What is Polymorphism?
 The derivation of the word Polymorphism is from two different Greek words- poly and
morphs.
 “Poly” means numerous, and “Morphs” means forms.
 Polymorphism means innumerable forms.
 Polymorphism, is one of the most significant features of Object-Oriented Programming
Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
1. Method Overloading
2. Method Overriding
What is Method Overloading in Java?
 Method overloading is the process that can create multiple methods of the same name
in the same class, and all the methods work in different ways.
 Method overloading occurs when there is more than one method of the same name in
the class.
 Method Overloading is when a class has multiple methods with the same name, but the
number, types, and order of parameters and the return type of the methods are different.
 Java allows the user freedom to use the same name for various functions as long as it
can distinguish between them by the type and number of parameters.

class Shapes {
public void area() {
System.out.println("Find area ");
}
public void area(int r) {
System.out.println("Circle area = "+3.14*r*r);
}

public void area(double b, double h) {


System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b) {
System.out.println("Rectangle area="+l*b);
}
}

class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object

myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);

}
}
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12

What is Method Overriding in Java?


 Method overriding is the process when the subclass or a child class has the same method
as declared in the parent class.
 Runtime polymorphism in Java is also popularly known as Dynamic Binding or
Dynamic Method Dispatch.
 In this process, the call to an overridden method is resolved dynamically at runtime
rather than at compile-time.
 we can achieve Runtime polymorphism via Method Overriding.
 Method Overriding is done when a child or a subclass has a method with the same
name, parameters, and return type as the parent or the superclass; then that function
overrides the function in the superclass.
 if the subclass provides its definition to a method already present in the superclass; then
that function in the base class is said to be overridden.
 it should be noted that runtime polymorphism can only be achieved through functions
and not data members.
 Overriding is done by using a reference variable of the superclass. The method to be
called is determined based on the object which is being referred to by the reference
variable. This is also known as Upcasting.
 Upcasting takes place when the Parent class’s reference variable refers to the object of
the child class.
Example of overriding
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is moving");}
}
//Creating a child class
class Car2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("car is running safely");}

public static void main(String args[]){


Car2 obj = new Car2();//creating object
obj.run();//calling method
}
}
Output:
Car is running safely
Example of overriding using upcasting

class Car
{
void run()
{
System.out.println(“ running”);
}
}
class innova extends Car
{
void run();
{
System.out.println(“ running fast at 120km”);
}
public static void main(String args[])
{
Car c = new innova(); //upcasting
c.run();
}
}
The output of the following program will be;
Running fast at 120 km.

Polymorphism in Java can be classified into two types, i.e:


1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism

What is Compile-Time Polymorphism in Java?


 Compile Time Polymorphism In Java is also known as Static Polymorphism.
 the call to the method is resolved at compile-time.
 Compile-Time polymorphism is achieved through Method Overloading.

 This type of polymorphism can also be achieved through Operator Overloading.


 Java does not support Operator Overloading.

What is Runtime Polymorphism in Java?


• Runtime polymorphism in Java is also popularly known as Dynamic Binding or
Dynamic Method Dispatch.
• In this process, the call to an overridden method is resolved dynamically at runtime
rather than at compile-time.
• we can achieve Runtime polymorphism via Method Overriding.
• Method Overriding is done when a child or a subclass has a method with the same
name, parameters, and return type as the parent or the superclass; then that function overrides
the function in the superclass.
• if the subclass provides its definition to a method already present in the superclass; then
that function in the base class is said to be overridden.
• it should be noted that runtime polymorphism can only be achieved through functions
and not data members.
• Overriding is done by using a reference variable of the superclass. The method to be
called is determined based on the object which is being referred to by the reference variable.
This is also known as Upcasting.
• Upcasting takes place when the Parent class’s reference variable refers to the object of
the child class.

Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Syntax:

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Example:

public class RecursionExample3 {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}

Output:
Factorial of 5 is: 120

Java code for multiplication table using two


dimensional array and nested for loop.

public class MultiplicationTableUsingArray


{
public static void main(String[] args)
{
int[][] arrMultipleTable = new int[10][10];
int row = 1, column = 1;
for(int a = 0; a < arrMultipleTable.length; a++)
{
for(int b = 0; b < arrMultipleTable[a].length; b++)
{
arrMultipleTable[a][b] = row * column;
column = column + 1;
}
row = row + 1;
column = 1;
}
for(int a = 0; a < arrMultipleTable.length; a++)
{
for(int b = 0; b < arrMultipleTable[a].length; b++)
{
System.out.print(" " + arrMultipleTable[a][b] + "\t ");
}
System.out.print("\n");
}
}
}

You might also like