Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views41 pages

OOPS Unit 2

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, methods, and inheritance. It explains the characteristics of objects, the structure of classes, and various ways to initialize objects, as well as the significance of methods, including static and instance methods, and method overloading. Additionally, it covers abstract methods, factory methods, and the use of access specifiers in method declarations.

Uploaded by

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

OOPS Unit 2

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, methods, and inheritance. It explains the characteristics of objects, the structure of classes, and various ways to initialize objects, as well as the significance of methods, including static and instance methods, and method overloading. Additionally, it covers abstract methods, factory methods, and the use of access specifiers in method declarations.

Uploaded by

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

UNIT II

OBJECT-ORIENTED PROGRAMMING, INTERFACES AND INHERITANCE

Working with Objects - Implementing Classes - Object Construction - Static Variables and Methods – Packages - Nested
Classes – Abstract Class - Interfaces – Static, Default and Private Methods – Local and Anonymous Classes – Inheritance
– Extending a class - Object: The Cosmic Superclass – Wrapper classes.

Working with Objects:

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

An object has three characteristics:

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


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

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

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an
object is the instance(result) of a class.

o An object is a real-world entity.


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

What is a class in Java:

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

A class in Java can contain:

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. That is why it is
known as an instance variable.

Method in Java

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

new keyword in Java

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

Example: main within the class

//Java Program to illustrate how to define a class and fields


//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:

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.

//Java Program to demonstrate having 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);
}
}

//Output

null

Implementing Classes

3 Ways to initialize object

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

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object.

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
}
}
// Output: 101 Sonoo
We can also 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);
}
}

Output:

101 Sonoo

102 Amit

2) Object and Class Example: Initialization through method

n this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insert Record 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();
}
}
Output:

111 Karan

222 Aryan

As you can see in the above figure, object gets the memory in heap memory area. The reference variable
refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer
to the objects allocated in memory.

3) Object and Class Example: Initialization through a constructor

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();
}
}

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0
Object Construction

There are many ways to create an object in java. They are:

o By new keyword By newInstance() method


o By clone() method By deserialization
o By factory method etc.

Anonymous object:

An object which has no reference is known as an anonymous object. It can be used at the time of object
creation only.

new Calculation();//anonymous object


Calling method through a reference:

Calculation c=new Calculation();


c.fact(5);
Calling method through an anonymous object:
new Calculation().fact(5);
Example:
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial is 120

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of reference variables:

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

//Java Program to illustrate the use of Rectangle class which


//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output: 55 45

Method in Java

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. It is used to achieve the reusability of code. We write a method once and use it many times.

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

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

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

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.

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.

Naming a Method:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

Types of Method:

o Predefined Method
o User-defined Method

Predefined Method:

In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
} // The maximum number is: 9
User-defined Method:

//user defined method


public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
How to Call or Invoke a User-defined Method:

import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}

Addition.java

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
} // The sum of a and b is= 24

Static Method:

A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using
the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It is invoked by using the class
name. The best example of a static method is the main() method.

Example of static method

Display.java

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Instance Method:
The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or
invoking the instance method, it is necessary to create an object of its class.

InstanceMethodExample.java
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
} // The sum is 25

There are two types of instance method:

o Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method.
We can easily identify it because the method is prefixed with the word get. It is also known as getters.
It returns the value of the private field. It is used to get the value of the private field.

public int getId()


{
return Id;
}
o Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can
easily identify it because the method is prefixed with the word set. It is also known as setters or
modifiers. It does not return anything. It accepts a parameter of the same data type that depends on
the field. It is used to set the value of the private field.

public void setRoll(int roll)


{
this.roll = roll;
}
Abstract Method:
The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. To create an abstract
method, we use the keyword abstract.

Syntax

abstract void method_name();

Demo.java

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}

Output: Abstract method

Factory method:

It is a method that returns an object to the class to which it belongs. All static methods are factory methods.
For example, NumberFormat obj = NumberFormat.getNumberInstance();
Method Overloading in Java:

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

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

• By changing number of arguments


• By changing the data type

By changing number of arguments

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
By changing the data type

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

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

Rules defined for the constructor.

• Constructor name must be the same as its class name


• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java:

• Default constructor (no-arg constructor)


• Parameterized constructor

Java Default Constructor

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

Syntax of default constructor:

<class_name>(){}

//Java Program to create and call a default constructor


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

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

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
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.

//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);}

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();
}
}
// 111, Karan
222, Aryan

Constructor Overloading in Java:

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They
are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the
number of parameters in the list and their types.

//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();
}
}

Difference between static and non-static variable:

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the class.
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();
}
}
Output:

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:

Why is the Java main method static?

It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object
first then call main() method that will lead the problem of extra memory allocation.
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.
• If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

Let's understand the problem if we don't use this keyword by the example given below:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
In the above example, parameters (formal arguments) and instance variables are same. o, we are using this keyword to
distinguish local variable and instance variable.

//Output: 0 null 0.0


0 null 0.0

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

Program where this keyword is not required


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

class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
//Output: 111 ankit 5000.0
112 sumit 6000.0
2) this: to invoke current class method

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

Java Package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

Syntax:
javac -d directory javafilename

For example: javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory,
you can use . (dot).

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
current folder.

How to run java package program:

Use fully qualified name

e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;

import package.classname;

fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); }
}
3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to
import.

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Sequence of the program must be package then import then class.

Subpackage in java:

• Package inside the package is called the subpackage.


• It should be created to categorize the package further.
• Sun Microsystem has definded a package named java that contains many classes like System, String, Reader,
Writer, Socket etc.
• Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output
related classes in io package, Server and ServerSocket classes in net packages and so on.
• The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.

Example:

package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.

o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.

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.

Why use inheritance in java

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


• For Code Reusability.

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java
specifies the accessibility or scope of a field, method, constructor, or class.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.
1) Private:
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the instance of that class from outside the class.

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It
cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than
protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.

3) Protected

• The protected access modifier is accessible within package and outside the package but through inheritance
only.
• The protected access modifier can be applied on the data member, method and constructor. It can't be applied
on the class.
• It provides more accessibility than the default modifer.

n this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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
}
}
Types of Nested classes in Java:

Java static nested class

A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data
members and methods. It can be accessed by outer class name.

2) It can access static data members of the outer class, including private.
3) The static nested class cannot access non-static (instance) data members or

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

In this example, you need to create the instance of static nested class because it has instance method msg(). But you
don't need to create the object of the Outer class because the nested class is static and static properties, methods, or
classes can be accessed without an object.

Java Member Inner class

A non-static class that is created inside a class but outside a method is called member inner class. It is also
known as a regular inner class. It can be declared with access modifiers like public, default, private, and
protected.

Syntax:

class Outer{
//code
class Inner{
//code
}
}

Example:

class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
} // The data is 30
Java Local inner class

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are
defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop, or an if clause

public class localInner1{


private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a single object is created. An
anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading
methods of a class or interface, without having to actually subclass a class.

Java Anonymous inner class can be created in two ways:

1) Class (may be abstract or concrete).


2) Interface

Java anonymous inner class example using class

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Java anonymous inner class example using interface

interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Inheritance in Java

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

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

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.

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.
Example:

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

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.

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();
}}
// barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below,
BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
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();
}}

// weeping...
barking...
eating...
Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.

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

• Abstract class (0 to 100%)


• Interface (100%)
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).

• 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{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

abstract void printStatus(); //no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by
the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

//running safely

Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
Another example of Abstract class in java

File: TestBank.java

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
// Rate of Interest is: 7 %
Rate of Interest is: 8 %

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

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
// bike is created
running safely..
gear changed

Interface in Java

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

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

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

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.

Syntax:

interface <interface_name>{

// declare constant fields

// declare methods that abstract

// by default.

The relationship between classes and interfaces


Java Interface Example: Bank

File: TestInterface2.java

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
// ROI: 9.15

Multiple inheritance in Java by interface:

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
// Output:Hello
Welcome
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:

interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
} // Hello
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

You might also like