You are on page 1of 34

UNIT-2 JAVA

ACCESS MODIFIER :

• In Java, the access specifiers (also known as access modifiers)


used to restrict the scope or accessibility of a class, constructor,
variable, method or data member of class and interface.

• In Java, the access to classes, constructors, methods and fields


are regulated using access modifiers i.e. a class can control what
information or data can be accessible by other classes.

• To take advantage of encapsulation, we should minimize access


whenever possible.

TYPES OF MODIFIER:

• default (or) no modifier

• public

• protected

• private

Public Specifier

• The public members can be accessed everywhere.

• When methods, variables, classes, and so on are declared public,


then we can access them from anywhere. The public access
modifier has no scope restriction. For example,

Example public specifier

public class Animal {


public int legCount;

public void display()

{ System.out.println("I am an animal.");

System.out.println("I have " + legCount + " legs.");

}}

public class Main

{ public static void main( String[] args )

Animal animal = new Animal();

animal.legCount = 4;

animal.display(); } }

OUTPUT

I am an animal.

I have 4 legs.

Private Specifier

• The private members can be accessed only inside the same class.

• When variables and methods are declared private, they cannot


be accessed outside of the class.

Example of Private Specifier

class Data

private String name;

}
public class Main

{ public static void main(String[] main)

{Data Data d = new Data();

class d.name = "Programiz"; }

OUTPUT:

Main.java:18: error: name has private access in

Data d.name = "Programiz";

NOTE- The error is generated because we are trying to access the


private variable of the Data class from the Main class.

Protected Specifier

• The protected members are accessible to every child class (same


package or other packages).

• When methods and data members are declared protected, we


can access them within the same package as well as from
subclasses. For example,

Example of Protected Specifier

class Animal {

protected void display()

{ System.out.println("I am an animal"); } }

class Dog extends Animal {

public static void main(String[ ] args)

{Dog dog = new Dog();


dog.display(); } }

OUTPUT : I am an animal

NOTE :- We cannot declare classes or interfaces protected in Java.

Default Specifier:

The default members are accessible within the same package but not
outside the package.

If we do not explicitly specify any access modifier for classes, methods,


variables etc, then by default the default access modifier is considered.
For example

Example of Default Specifier

package defaultPackage;

class Logger {

void message()

{ System.out.println("This is a message"); }

Note:-Here, the Logger class has the default access modifier. And the
class is visible to all the classes that belong to
the defaultPackage package.

However, if we try to use the Logger class in another class outside of


defaultPackage, we will get a compilation error.

Data member
• Data members are the data variables and member functions are
the functions used to manipulate these variables and together
these data members and member functions defines the
properties and behavior of the objects in a Class

Types of Data Members :

• We know that a class is a collection of data members and


methods. In java programming we have two types of data
members they are

1. Instance/non-static data member

2. Static data members

Instance/non-static data member

• Instance data members are those whose memory space is


created each and every time whenever an object is created.

• Instance data members are always meant for storing specific


values.

• Instance data members are always meant for storing specific


values.
Syntax: -
Data type v1, v2, v3 ………. Vn;

static data members

• Static data members are those whose memory space is created


only once, whenever the class is loaded in the main memory
irrespective of no of objects are created.

• Static data members are meant for storing common values.


• Programmatically static data member declaration must be
preceded by static keyword.

• Syntax: -
static data type v1, v2, v3 ………. Vn;

static data members

• Each and every static data member must be access with


respective class name.
Ex: -
Class name.static data member name

• Static data member are also known as Class Level Data


Members because they depends on class name and independent
from object name

Ex: -
static String cname;
static String CapIndia;

Types of Methods: -

we know that each and every method is meant for performing some
operation. In java programming we have two types of methods they
are

1. Instance/ non – static methods


2. Static methods

Instance/ non – static methods

Instance methods: -

1. Instance methods are always recommended to


perform repeated operations like reading records from the file,
reading records from the data base etc…

2. Programmatically instance methods definitions should not be


preceded by a
keyword static.

Syntax: -
Return type method name (list of parameters if any)
{
Block of statements;
}

3. Each and every instance method must be access with


respective Object name.

4. Result of instance method is not sharable

Static methods:

• Static methods: -

1. Static methods are always which are recommended to


perform one operation like
opening the files, obtaining a data base connection etc .

2. Programmatically static methods definitions must be


preceded by static keyword.

Syntax: -
Static Return type method name (list of parameters if any)

{
Block of statements;
}
3. Each and every static method must be accessed with
respect class name.

4. Result set of static method always sharable

Java Inner Classes (Nested Classes)

1. Java Inner classes


2. Advantage of Inner class
3. Difference between nested class and inner class
4. Types of 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

1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

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.

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

The idea behind inheritance in Java is that you can create


new classes that are built upon existing classes. When you inherit from
an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class
also.

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


a parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be


achieved).
o For Code Reusability.

Terms used in Inheritance

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

1. class Subclass-name extends Superclass-name


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

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.

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.

Java Inheritance Example


As displayed in the above figure, Programmer is the subclass and
Employee is the superclass. The relationship between the two classes
is Programmer IS-A Employee. It means that Programmer is a type of
Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now

Programmer salary is:40000.0


Bonus of programmer is:10000
In the above 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

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.

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

When one class inherits multiple classes, it is known as multiple


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

File: TestInheritance.java

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

Output:
barking...
eating...
Multilevel Inheritance Example

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


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

File: TestInheritance2.java

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

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

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


as hierarchical inheritance. In the example given below, Dog and Cat
classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java

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

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple


inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class


inherits A and B classes. If A and B classes have the same method and
you call it from child class object, there will be ambiguity to call the
method of A or B class.

Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of


the method that has been declared by one of its parent class, it is
known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific


implementation of a method which is already provided by its
superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent
class.
3. There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we


don't use method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
16. }
Test it Now

Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run()


method in subclass that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as


defined in the parent class but it has some specific implementation.
The name and parameter of the method are the same, and there is IS-
A relationship between the classes, so there is method overriding.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
Test it Now

Output:

Bike is running safely

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.

Whenever you create the instance of subclass, an instance of parent


class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.
1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of


parent class. It is used if parent class and child class have same fields.

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

Output:

black
white

In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of
current class by default. To access the parent property, we need to use
super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class.
In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it Now

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of
Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

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

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

Output:

animal is created
dog is created

Binding

• Association of method call with the method body is known as


binding in Java.

• Connecting a method call to the method body is known as


binding.

• Binding is a mechanism creating link between method call and


method actual implementation.

Types of Binding

There are basically two type of binding

1. Static Binding (also known as Early Binding).

2. Dynamic Binding (also known as Late Binding).

Static Binding

• When type of an object is determined at compile time ,it is


known as Static Binding
• The binding which can be resolved at compile time by compiler
is known as static or early binding.

• Binding of all the static, private and final methods is done at


compile-time .

Why binding of static, final and private methods is always a static


binding?

• Static binding is better performance wise (no extra overhead is


required).

• Compiler knows that all such methods cannot be overridden and


will always be accessed by object of local class.

• Hence compiler doesn’t have any difficulty to determine object


of class (local class for sure). That’s the reason binding for such
methods is static.

Example Static binding

public class New_Class {


public static class baseclass {
static void print()
{
System.out.println("print in baseclass.");
}
}
public static class derivedclass extends baseclass {
static void print()
{
System.out.println("print in derivedclass.");
}
}
public static void main(String[] args)
{
baseclass A = new baseclass();
baseclass B = new derivedclass();
A.print();
B.print();
}

Output:

print in baseclass.
print in baseclass.

• In both cases print method of baseclass is called.

• We have created one object of derivedclass and one object of


baseclass with the reference of the baseclass.

• Since the print method of baseclass is static, compiler knows that


it will not be overridden in derivedclasses and hence compiler
knows during compile time which print method to call and hence
no ambiguity.

Dynamic Binding

• dynamic binding, the method call is bonded to the method body


at runtime.

• In Dynamic binding compiler doesn’t decide the method to be


called.

• Overriding is a perfect example of dynamic binding. In overriding


both parent and child classes have same method . Let’s see by an
example

Example Dynamic binding


public class New_Class {
public static class baseclass {
void print()
{
System.out.println("print in baseclass.");
}
}

public static class derivedclass extends baseclass {


@Override
void print()
{
System.out.println("print in derivedclass.");
}
}

public static void main(String[] args)


{
baseclass A = new baseclass();
baseclass B = new derivedclass();
A.print();
B.print();
}
}

Output:

print in baseclass.
print in derivedclass.

• Methods are not static in this code.

• During compilation, the compiler has no idea as to which print


has to be called since compiler goes only by referencing variable
not by type of object and therefore the binding would be
delayed to runtime and therefore the corresponding version of
print will be called based on type on object.
Important Points

• private, final and static members (methods and variables) use


static binding while for virtual methods (In Java methods are
virtual by default) binding is done during run time based upon
run time object.

• Static binding uses Type information for binding while Dynamic


binding uses Objects to resolve binding.

• Overloaded methods are resolved (deciding which method to be


called when there are multiple methods with same name) using
static binding while overridden methods using dynamic binding,
i.e, at run time.

What is Thread ?

1. A thread is also known as a lightweight process

2. we can say the smallest part of the process that allows a program
to operate more efficiently by running multiple tasks
simultaneously.

3. In order to perform complicated tasks in the background, we


used the Thread concept in Java.

4. All the tasks are executed without affecting the main program. In
a program or process, all the threads have their own separate
path for execution, so each thread of a process is independent.

5. Another benefit of using thread is that if a thread gets an


exception or an error at the time of its execution, it doesn't affect
the execution of the other threads.
In shortly the Thread is a:

1. Feature through which we can perform multiple activities within


a single process.

2. Lightweight process.

3. Series of executed statements.

4. Nested sequence of method calls.

States of Threads / Thread Model


States of Thread

1. New(new borned )-> When a thread is created (by new


statement ) but not yet to run, it is called in Newborn state.

2. Runnable :->The Runnable state means that a thread is ready to


run and is awaiting for the control of the processor or in other
words, threads are in this state in a queue and wait their turns to
be executed..

3. Running -> Running means that the thread has control of the
processor, its code is currently being executed and thread will
continue in this state until it get preempted by a higher priority
thread, or until it relinquishes control

4. Blocked : A thread is Blocked means that it is being prevented


from the Runnable ( or Running) state and is waiting for some
event in order for it to re-enter the scheduling queue.

5. Dead/Terminated : A thread is Dead when it finishes its


execution or is stopped (killed) by another thread

Methods

1. start ( ) : A newborn thread with this method enter into Runnable


state and Java run time create a system thread context and starts
it running. This method for a thread object can be called once
only
2. stop( ) : This method causes a thread to stop immediately. This is
often an abrupt way to end a thread.

3. suspend( ) : This method is different from stop( ) method. It takes


the thread and causes it to stop running and later on can be
restored by calling it again.

4. resume ( ) : This method is used to revive a suspended thread.


There is no gurantee that the thread will start running right way,
since there might be a higher priority thread running already, but,
resume()causes the thread to become eligible for running.

5. sleep (int n ) : This method causes the run time to put the current
thread to sleep for n milliseconds. After n milliseconds have
expired, this thread will become elligible to run again.

6. yield( ) : The yield() method causes the run time to switch the
context from the current thread to the next available runnable
thread. This is one way to ensure that the threads at lower priority
do not get started.

### Multithreading Support in Java:

#### 1. **Introduction to Multithreading:**

- **Multithreading:** The concurrent execution of more than one


sequential set of instructions within a process.

- **Thread:** A thread is the smallest unit of execution within a


process, representing an independent path of execution.

- **Advantages of Multithreading:**

- Improved performance by utilizing multiple cores.

- Enhanced responsiveness in user interfaces.


- Efficient resource utilization.

#### 2. **Creating and Controlling Threads:**

- **Extending Thread Class:**

- To create a thread, a class can extend the `Thread` class and


override the `run()` method.

- Example:

```java

class MyThread extends Thread {

public void run() {

// Code to be executed in a separate thread

// Creating and starting a thread

MyThread myThread = new MyThread();

myThread.start();

```

- **Implementing Runnable Interface:**

- Alternatively, a class can implement the `Runnable` interface and


provide the implementation of `run()`.

- Example:

```java

class MyRunnable implements Runnable {


public void run() {

// Code to be executed in a separate thread

// Creating and starting a thread using Runnable

Thread myThread = new Thread(new MyRunnable());

myThread.start();

```

#### 3. **Managing Thread Pools with Thread Groups:**

- **Thread Pool:**

- A pool of worker threads that are ready to execute tasks.

- Improves performance by reusing existing threads.

- **Creating a Thread Pool:**

- The `ExecutorService` interface provides methods for managing


thread pools.

- Example:

```java

ExecutorService executor = Executors.newFixedThreadPool(5);

```

- **Submitting Tasks to Thread Pool:**

- Tasks are submitted to the thread pool for execution.


- Example:

```java

executor.submit(() -> {

// Task to be executed

});

```

#### 4. **Distributing Work in Multiple Threads for Faster Execution:**

- **Divide and Conquer:**

- Break a large problem into smaller, more manageable sub-


problems and solve them concurrently.

- **Example - Parallel Processing:**

- Assume we have a large array of data, and we want to process it


using multiple threads.

- ```java

int[] data = { /* large array of data */ };

int cores = Runtime.getRuntime().availableProcessors();

// Divide data into segments for each core

int segmentSize = data.length / cores;

// Create and start threads to process each segment

for (int i = 0; i < cores; i++) {

int startIndex = i * segmentSize;


int endIndex = (i == cores - 1) ? data.length : (i + 1) *
segmentSize;

Thread thread = new Thread(() -> processSegment(data,


startIndex, endIndex));

thread.start();

```

#### 5. **Distributing Work in Multiple Threads Related to I/O:**

- **Asynchronous I/O:**

- Use multiple threads to perform I/O operations concurrently


without blocking.

- **Example - Asynchronous File Reading:**

- Asynchronous I/O operations are supported by the `java.nio`


package.

- ```java

AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(Paths.get("file.txt"));

ByteBuffer buffer = ByteBuffer.allocate(1024);

long position = 0;

// Initiating asynchronous read operation


fileChannel.read(buffer, position, buffer, new
CompletionHandler<Integer, ByteBuffer>() {

public void completed(Integer result, ByteBuffer attachment) {

// Process the read data

public void failed(Throwable exc, ByteBuffer attachment) {

// Handle failure

});

```

#### 6. **Thread Safety and Synchronization:**

- **Thread Safety:** Ensuring that shared resources can be accessed


by multiple threads without interference.

- **Synchronization:** Controlling access to shared resources to


avoid data inconsistency.

- **Example - Synchronized Method:**

- Using the `synchronized` keyword to ensure atomicity.

- ```java

class Counter {

private int count = 0;

// Synchronized method

public synchronized void increment() {


count++;

```

You might also like