Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Java Material

OOPS Concepts
1. Abstraction
Abstraction is the concept of hiding the internal details and describing things in
simple terms. For example, a method that adds two integers. The internal processing
of the method is hidden from the outer world. There are many ways to achieve
abstraction in object-oriented programmings, such as encapsulation and inheritance.
A Java program is also a great example of abstraction. Here java takes care of
converting simple statements to machine language and hides the inner
implementation details from the outer world.

Abstraction in Java is implemented through interfaces and abstract classes. They


are used to create a base implementation or contract for the actual implementation
classes.

Car.java: Base interface or abstract class

package com.journaldev.oops.abstraction;

public interface Car {

void turnOnCar();

void turnOffCar();

String getCarType();
}

ManualCar.java, AutomaticCar.java: implementation classes of Car.

package com.journaldev.oops.abstraction;

public class ManualCar implements Car {

private String carType = "Manual";

@Override
public void turnOnCar() {
System.out.println("turn on the manual car");
}

@Override
public void turnOffCar() {
System.out.println("turn off the manual car");
}
@Override
public String getCarType() {
return this.carType;
}
}

package com.journaldev.oops.abstraction;

public class AutomaticCar implements Car {

private String carType = "Automatic";

@Override
public void turnOnCar() {
System.out.println("turn on the automatic car");
}

@Override
public void turnOffCar() {
System.out.println("turn off the automatic car");
}

@Override
public String getCarType() {
return this.carType;
}
}

User Program: Let’s look at a test program where the Car functions will be used.

package com.journaldev.oops.abstraction;

public class CarTest {

public static void main(String[] args) {


Car car1 = new ManualCar();
Car car2 = new AutomaticCar();

car1.turnOnCar();
car1.turnOffCar();
System.out.println(car1.getCarType());

car2.turnOnCar();
car2.turnOffCar();
System.out.println(car2.getCarType());

}
The client program only knows about the Car and the functions that the Car
provides. The internal implementation details are hidden from the client program.
2. Encapsulation
Encapsulation is the technique used to implement abstraction in object-oriented
programming. Encapsulation is used for access restriction to class members and
methods.
Access modifier keywords are used for encapsulation in object oriented
programming. For example, encapsulation in java is achieved
using private, protected and public keywords.

3. Polymorphism
Polymorphism is the concept where an object behaves differently in different
situations. There are two types of polymorphism – compile time polymorphism and
runtime polymorphism.
Compile-time polymorphism is achieved by method overloading. For example, we
can have a class as below.
public class Circle {

public void draw(){


System.out.println("Drwaing circle with default
color Black and diameter 1 cm.");
}

public void draw(int diameter){


System.out.println("Drwaing circle with default
color Black and diameter"+diameter+" cm.");
}

public void draw(int diameter, String color){


System.out.println("Drwaing circle with
color"+color+" and diameter"+diameter+" cm.");
}
}
Here we have multiple draw methods but they have different behavior. This is a
case of method overloading because all the methods name is same and arguments
are different. Here compiler will be able to identify the method to invoke at compile-
time, hence it’s called compile-time polymorphism.
Runtime polymorphism is implemented when we have an “IS-A” relationship
between objects. This is also called a method overriding because the subclass has
to override the superclass method for runtime polymorphism.
If we are working in terms of the superclass, the actual implementation class is
decided at runtime. The compiler is not able to decide which class method will be
invoked. This decision is done at runtime, hence the name as runtime polymorphism
or dynamic method dispatch.
package com.journaldev.test;

public interface Shape {

public void draw();


}
package com.journaldev.test;

public class Circle implements Shape{

@Override
public void draw(){
System.out.println("Drwaing circle");
}

}
package com.journaldev.test;

public class Square implements Shape {

@Override
public void draw() {
System.out.println("Drawing Square");
}

}
Shape is the superclass and there are two subclasses Circle and Square. Below
is an example of runtime polymorphism.
Shape sh = new Circle();
sh.draw();

Shape sh1 = getShape(); //some third party logic to determine


shape
sh1.draw();

In the above examples, java compiler doesn’t know the actual implementation class
of Shape that will be used at runtime, hence runtime polymorphism.

4. Inheritance
Inheritance is the object-oriented programming concept where an object is based on
another object. Inheritance is the mechanism of code reuse. The object that is
getting inherited is called the superclass and the object that inherits the superclass is
called a subclass.
We use extends keyword in java to implement inheritance. Below is a simple
example of inheritance in java.
package com.journaldev.java.examples1;

class SuperClassA {

public void foo(){


System.out.println("SuperClassA");
}

class SubClassB extends SuperClassA{

public void bar(){


System.out.println("SubClassB");
}

public class Test {


public static void main(String args[]){
SubClassB a = new SubClassB();

a.foo();
a.bar();
}
}

Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.

Important terminology:
 Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
 Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
How to use inheritance in Java
The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is
a derived class which extends Bicycle class and class Test is a driver class to run program.

//Java program to illustrate the 


// concept of inheritance
  
// base class
class Bicycle 
{
    // the Bicycle class has two fields
    public int gear;
    public int speed;
          
    // the Bicycle class has one constructor
    public Bicycle(int gear, int speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
          
    // the Bicycle class has three methods
    public void applyBrake(int decrement)
    {
        speed -= decrement;
    }
          
    public void speedUp(int increment)
    {
        speed += increment;
    }
      
    // toString() method to print info of Bicycle
    public String toString() 
    {
        return("No of gears are "+gear
                +"\n"
                + "speed of bicycle is "+speed);
    } 
}
  
// derived class
class MountainBike extends Bicycle 
{
      
    // the MountainBike subclass adds one more field
    public int seatHeight;
  
    // the MountainBike subclass has one constructor
    public MountainBike(int gear,int speed,
                        int startHeight)
    {
        // invoking base-class(Bicycle) constructor
        super(gear, speed);
        seatHeight = startHeight;
    } 
          
    // the MountainBike subclass adds one more method
    public void setHeight(int newValue)
    {
        seatHeight = newValue;
    } 
      
    // overriding toString() method
    // of Bicycle to print more info
    @Override
    public String toString()
    {
        return (super.toString()+
                "\nseat height is "+seatHeight);
    }
      
}
  
// driver class
public class Test 
{
    public static void main(String args[]) 
    {
          
        MountainBike mb = new MountainBike(3, 100, 25);
        System.out.println(mb.toString());
              
    }
}
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25

In above program, when an object of MountainBike class is created, a copy of the all
methods and fields of the superclass acquire memory in this object. That is why, by using
the object of the subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For
more, refer Java Object Creation of Inherited Class.

In practice, inheritance and polymorphism are used together in java to achieve fast


performance and readability of code.

Types of Inheritance in Java


Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit the features of
one superclass. In image below, the class A serves as a base class for the derived class
B.

//Java program to illustrate the 


// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
// Driver class
public class Main
{
    public static void main(String[] args)
    {
        two g = new two();
        g.print_geek();
        g.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks

2. Multilevel Inheritance : In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base class to
other class. In below image, the class A serves as a base class for the derived class B,
which in turn serves as a base class for the derived class C. In Java, a class cannot
directly access the grandparent’s members.

// Java program to illustrate the 


// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
  
class three extends two
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        three g = new three();
        g.print_geek();
        g.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one sub class.In below image, the class A serves
as a base class for the derived class B,C and D.

// Java program to illustrate the 


// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
  
class three extends one
{
    /*............*/
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        three g = new three();
        g.print_geek();
        two t = new two();
        t.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class
can have more than one superclass and inherit features from all parent classes. Please
note that Java does not support multiple inheritance with classes. In java, we can
achieve multiple inheritance only through Interfaces. In image below, Class C is derived
from interface A and B.

// Java program to illustrate the 


// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
   
interface one
{
    public void print_geek();
}
   
interface two
{
    public void print_for();
}
   
interface three extends one,two
{
    public void print_geek();
}
class child implements three
{
    @Override
    public void print_geek() {
        System.out.println("Geeks");
    }
   
    public void print_for()
    {
        System.out.println("for");
    }
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        child c = new child();
        c.print_geek();
        c.print_for();
        c.print_geek();
    }
}
Output:
Geeks
for
Geeks
5. Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the
above types of inheritance. Since java doesn’t support multiple inheritance with
classes, the hybrid inheritance is also not possible with classes. In java, we can achieve
hybrid inheritance only through Interfaces.

Important facts about inheritance in Java


 Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.
 Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.
 Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
 Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.
What all can be done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement them
with new members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same signature as
the one in the superclass, thus overriding it (as in example above, toString() method is
overridden).
 We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.

Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface
 

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create
an object of our new class and call start() method to start the execution of a thread. Start()
invokes the run() method on the Thread object.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread
{
    public void run()
    {
        try
        {
            // Displaying the thread that is running
            System.out.println ("Thread " +
                  Thread.currentThread().getId() +
                  " is running");
  
        }
        catch (Exception e)
        {
            // Throwing an exception
            System.out.println ("Exception is caught");
        }
    }
}
  
// Main Class
public class Multithread
{
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i=0; i<n; i++)
        {
            MultithreadingDemo object = new MultithreadingDemo();
            object.start();
        }
    }
}
Output :

Thread 8 is running
Thread 9 is running

Thread 10 is running

Thread 11 is running

Thread 12 is running

Thread 13 is running

Thread 14 is running

Thread 15 is running

 
Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

// Java code for thread creation by implementing


// the Runnable Interface
class MultithreadingDemo implements Runnable
{
    public void run()
    {
        try
        {
            // Displaying the thread that is running
            System.out.println ("Thread " +
                                Thread.currentThread().getId() +
                                " is running");
  
        }
        catch (Exception e)
        {
            // Throwing an exception
            System.out.println ("Exception is caught");
        }
    }
}
  
// Main Class
class Multithread
{
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i=0; i<n; i++)
        {
            Thread object = new Thread(new MultithreadingDemo());
            object.start();
        }
    }
}
Output :

Thread 8 is running

Thread 9 is running

Thread 10 is running

Thread 11 is running

Thread 12 is running

Thread 13 is running

Thread 14 is running

Thread 15 is running

Thread Class vs Runnable Interface

1. If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class
can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it


provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable
interface.

Difference between Multiprogramming, multitasking, multithreading and


multiprocessing
1. Multiprogramming – A computer running more than one program at a time (like running
Excel and Firefox simultaneously).
2. Multiprocessing – A computer using more than one CPU at a time.
3. Multitasking – Tasks sharing a common resource (like 1 CPU).
4. Multithreading is an extension of multitasking.
1. Multi programming –
In a modern computing system, there are usually several concurrent application processes
which want to execute. Now it is the responsibility of the Operating System to manage all
the processes effectively and efficiently.
One of the most important aspects of an Operating System is to multi program.
In a computer system, there are multiple processes waiting to be executed, i.e. they are
waiting when the CPU will be allocated to them and they begin their execution. These
processes are also known as jobs. Now the main memory is too small to accommodate all of
these processes or jobs into it. Thus, these processes are initially kept in an area called job
pool. This job pool consists of all those processes awaiting allocation of main memory and
CPU.
CPU selects one job out of all these waiting jobs, brings it from the job pool to main memory
and starts executing it. The processor executes one job until it is interrupted by some
external factor or it goes for an I/O task.

Non-multi programmed system’s working –


 In a non multi programmed system, As soon as one job leaves the CPU and goes for some
other task (say I/O ), the CPU becomes idle. The CPU keeps waiting and waiting until this job
(which was executing earlier) comes back and resumes its execution with the CPU. So CPU
remains free for all this while.
 Now it has a drawback that the CPU remains idle for a very long period of time. Also, other
jobs which are waiting to be executed might not get a chance to execute because the CPU is
still allocated to the earlier job.
This poses a very serious problem that even though other jobs are ready to execute, CPU is not
allocated to them as the CPU is allocated to a job which is not even utilizing it (as it is busy in
I/O tasks).
 It cannot happen that one job is using the CPU for say 1 hour while the others have been
waiting in the queue for 5 hours. To avoid situations like this and come up with efficient
utilization of CPU, the concept of multi programming came up.
The main idea of multi programming is to maximize the CPU time.
Multi programmed system’s working –
 In a multi-programmed system, as soon as one job goes for an I/O task, the Operating
System interrupts that job, chooses another job from the job pool (waiting queue), gives CPU
to this new job and starts its execution. The previous job keeps doing its I/O operation while
this new job does CPU bound tasks. Now say the second job also goes for an I/O task, the CPU
chooses a third job and starts executing it. As soon as a job completes its I/O operation and
comes back for CPU tasks, the CPU is allocated to it.
 In this way, no CPU time is wasted by the system waiting for the I/O task to be completed.
Therefore, the ultimate goal of multi programming is to keep the CPU busy as long as there are
processes ready to execute. This way, multiple programs can be executed on a single
processor by executing a part of a program at one time, a part of another program after this,
then a part of another program and so on, hence executing multiple programs. Hence, the CPU
never remains idle.
In the image below, program A runs for some time and then goes to waiting state. In the
mean time program B begins its execution. So the CPU does not waste its resources and
gives program B an opportunity to run.

2. Multiprocessing –
In a uni-processor system, only one process executes at a time.
Multiprocessing is the use of two or more CPUs (processors) within a single Computer
system. The term also refers to the ability of a system to support more than one processor
within a single computer system. Now since there are multiple processors available,
multiple processes can be executed at a time. These multi processors share the computer
bus, sometimes the clock, memory and peripheral devices also.

Multi processing system’s working –


 With the help of multiprocessing, many processes can be executed simultaneously. Say
processes P1, P2, P3 and P4 are waiting for execution. Now in a single processor system, firstly
one process will execute, then the other, then the other and so on.
 But with multiprocessing, each process can be assigned to a different processor for its
execution. If its a dual-core processor (2 processors), two processes can be executed
simultaneously and thus will be two times faster, similarly a quad core processor will be four
times as fast as a single processor.
Why use multi processing –
 The main advantage of multiprocessor system is to get more work done in a shorter period
of time. These types of systems are used when very high speed is required to process a large
volume of data. Multi processing systems can save money in comparison to single processor
systems because the processors can share peripherals and power supplies.
 It also provides increased reliability in the sense that if one processor fails, the work does
not halt, it only slows down. e.g. if we have 10 processors and 1 fails, then the work does not
halt, rather the remaining 9 processors can share the work of the 10th processor. Thus the
whole system runs only 10 percent slower, rather than failing altogether.
Multiprocessing refers to the hardware (i.e., the CPU units) rather than the software (i.e.,
running processes). If the underlying hardware provides more than one processor then that
is multiprocessing. It is the ability of the system to leverage multiple processors’ computing
power.

Difference between Multi programming and Multi processing –


 A System can be both multi programmed by having multiple programs running at the same
time and multiprocessing by having more than one physical processor. The difference between
multiprocessing and multi programming is that Multiprocessing is basically executing multiple
processes at the same time on multiple processors, whereas multi programming is keeping
several programs in main memory and executing them concurrently using a single CPU only.
 Multiprocessing occurs by means of parallel processing whereas Multi programming occurs
by switching from one process to other (phenomenon called as context switching).
3. Multitasking –
As the name itself suggests, multi tasking refers to execution of multiple tasks (say
processes, programs, threads etc.) at a time. In the modern operating systems, we are able
to play MP3 music, edit documents in Microsoft Word, surf the Google Chrome all
simultaneously, this is accomplished by means of multi tasking.

Multitasking is a logical extension of multi programming. The major way in which


multitasking differs from multi programming is that multi programming works solely on the
concept of context switching whereas multitasking is based on time sharing alongside the
concept of context switching.

Multi tasking system’s working –


 In a time sharing system, each process is assigned some specific quantum of time for which a
process is meant to execute. Say there are 4 processes P1, P2, P3, P4 ready to execute. So each
of them are assigned some time quantum for which they will execute e.g time quantum of 5
nanoseconds (5 ns). As one process begins execution (say P2), it executes for that quantum of
time (5 ns). After 5 ns the CPU starts the execution of the other process (say P3) for the
specified quantum of time.
 Thus the CPU makes the processes to share time slices between them and execute
accordingly. As soon as time quantum of one process expires, another process begins its
execution.
 Here also basically a context switch is occurring but it is occurring so fast that the user is able
to interact with each program separately while it is running. This way, the user is given the
illusion that multiple processes/ tasks are executing simultaneously. But actually only one
process/ task is executing at a particular instant of time. In multitasking, time sharing is best
manifested because each running process takes only a fair quantum of the CPU time.
In a more general sense, multitasking refers to having multiple programs, processes, tasks,
threads running at the same time. This term is used in modern operating systems when
multiple tasks share a common processing resource (e.g., CPU and Memory).

 As depicted in the above image, At any time the CPU is executing only one task while other
tasks are waiting for their turn. The illusion of parallelism is achieved when the CPU is
reassigned to another task. i.e all the three tasks A, B and C are appearing to occur
simultaneously because of time sharing.
 So for multitasking to take place, firstly there should be multiprogramming i.e. presence of
multiple programs ready for execution. And secondly the concept of time sharing.
4. Multi threading –
A thread is a basic unit of CPU utilization. Multi threading is an execution model that allows
a single process to have multiple code segments (i.e., threads) running concurrently within
the “context” of that process.
e.g. VLC media player, where one thread is used for opening the VLC media player, one
thread for playing a particular song and another thread for adding new songs to the playlist.

Multi threading is the ability of a process to manage its use by more than one user at a time
and to manage multiple requests by the same user without having to have multiple copies
of the program.

Multi threading system’s working –


Example 1 –
 Say there is a web server which processes client requests. Now if it executes as a single
threaded process, then it will not be able to process multiple requests at a time. Firstly one
client will make its request and finish its execution and only then, the server will be able to
process another client request. This is really costly, time consuming and tiring task. To avoid
this, multi threading can be made use of.
 Now, whenever a new client request comes in, the web server simply creates a new thread
for processing this request and resumes its execution to hear more client requests. So the web
server has the task of listening to new client requests and creating threads for each individual
request. Each newly created thread processes one client request, thus reducing the burden on
web server.
Example 2 –
 We can think of threads as child processes that share the parent process resources but
execute independently. Now take the case of a GUI. Say we are performing a calculation on
the GUI (which is taking very long time to finish). Now we can not interact with the rest of the
GUI until this command finishes its execution. To be able to interact with the rest of the GUI,
this command of calculation should be assigned to a separate thread. So at this point of time,
2 threads will be executing i.e. one for calculation, and one for the rest of the GUI. Hence here
in a single process, we used multiple threads for multiple functionality.
The image below completely describes the VLC player example:

Advantages of Multi threading –


 Benefits of Multi threading include increased responsiveness. Since there are multiple
threads in a program, so if one thread is taking too long to execute or if it gets blocked, the
rest of the threads keep executing without any problem. Thus the whole program remains
responsive to the user by means of remaining threads.
 Another advantage of multi threading is that it is less costly. Creating brand new processes
and allocating resources is a time consuming task, but since threads share resources of the
parent process, creating threads and switching between them is comparatively easy. Hence
multi threading is the need of modern Operating Systems.

Immutable
Immutable class means that once an object is created, we cannot change its content. In
Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is
immutable. We can create our own immutable class as well.
Following are the requirements:

 The class must be declared as final (So that child classes can’t be created)
 Data members in the class must be declared as final (So that we can’t change the
value of it after object creation)
 A parameterized constructor
 Getter method for all the variables in it
 No setters(To not have the option to change the value of the instance variable)
Example to create Immutable class

// An immutable class
public final class Student
{
    final String name;
    final int regNo;
  
    public Student(String name, int regNo)
    {
        this.name = name;
        this.regNo = regNo;
    }
    public String getName()
    {
        return name;
    }
    public int getRegNo()
    {
        return regNo;
    }
}
  
// Driver class
class Test
{
    public static void main(String args[])
    {
        Student s = new Student("ABC", 101);
        System.out.println(s.getName());
        System.out.println(s.getRegNo());
  
        // Uncommenting below line causes error
        // s.regNo = 102;
    }
}
Output:
ABC

101
In this example, we have created a final class named Student. It has two final data members,
a parameterized constructor and getter methods. Please note that there is no setter method
here.
(In order to make it functional, create objects of Student class in the main function.)

Enum
Enumerations serve the purpose of representing a group of named constants in a
programming language. For example the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type
named Suit. Other examples include natural enumerated types (like the planets, days of the
week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as choices on a
menu, rounding modes, command line flags, etc. It is not necessary that the set of constants
in an enum type stay fixed for all time.
In Java (from 1.5), enums are represented using enum data type. Java enums are more
powerful than C/C++ enums . In Java, we can also add variables, methods and constructors
to it. The main objective of enum is to define our own data types(Enumerated Data Types).
Declaration of enum in java :
 Enum declaration can be done outside a Class or inside a Class but not inside a
Method.

// A simple enum example where enum is declared


// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
    RED, GREEN, BLUE;
}
  
public class Test
{
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
Output :
RED

// enum declaration inside a class.


public class Test
{
    enum Color
    {
        RED, GREEN, BLUE;
    }
  
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
Output :
RED
 First line inside enum should be list of constants and then other things like methods,
variables and constructor.
 According to Java naming conventions, it is recommended that we name constant
with all capital letters

Important points of enum :


 Every enum internally implemented by using Class.
 /* internally above enum Color is converted to
 class Color
 {
 public static final Color RED = new Color();
 public static final Color BLUE = new Color();
 public static final Color GREEN = new Color();
 }*/
 Every enum constant represents an object of type enum.
 enum type can be passed as an argument to switch statement.

// A Java program to demonstrate working on enum


// in switch case (Filename Test. Java)
import java.util.Scanner;
  
// An Enum class
enum Day
{
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY;
}
  
// Driver class that contains an object of "day" and
// main().
public class Test
{
    Day day;
  
    // Constructor
    public Test(Day day)
    {
        this.day = day;
    }
  
    // Prints a line about Day using switch
    public void dayIsLike()
    {
        switch (day)
        {
        case MONDAY:
            System.out.println("Mondays are bad.");
            break;
        case FRIDAY:
            System.out.println("Fridays are better.");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best.");
            break;
        default:
            System.out.println("Midweek days are so-so.");
            break;
        }
    }
  
    // Driver method
    public static void main(String[] args)
    {
        String str = "MONDAY";
        Test t1 = new Test(Day.valueOf(str));
        t1.dayIsLike();
    }
}
Output:
Mondays are bad.
 Every enum constant is always implicitly public static final. Since it is static, we can
access it by using enum Name. Since it is final, we can’t create child enums.
 We can declare main() method inside enum. Hence we can invoke enum directly
from the Command Prompt.

// A Java program to demonstrate that we can have


// main() inside enum class.
enum Color
{
    RED, GREEN, BLUE;
  
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
Output :
RED
Enum and Inheritance :
 All enums implicitly extend java.lang.Enum class. As a class can only
extend one parent in Java, so an enum cannot extend anything else.
 toString() method is overridden in java.lang.Enum class,which returns enum
constant name.
 enum can implement many interfaces.
values(), ordinal() and valueOf() methods :
 These methods are present inside java.lang.Enum.
 values() method can be used to return all values present inside enum.
 Order is important in enums.By using ordinal() method, each enum constant index
can be found, just like array index.
 valueOf() method returns the enum constant of the specified string value, if exists.

// Java program to demonstrate working of values(),


// ordinal() and valueOf()
enum Color
{
    RED, GREEN, BLUE;
}
  
public class Test
{
    public static void main(String[] args)
    {
        // Calling values()
        Color arr[] = Color.values();
  
        // enum with loop
        for (Color col : arr)
        {
            // Calling ordinal() to find index
            // of color.
            System.out.println(col + " at index "
                             + col.ordinal());
        }
  
        // Using valueOf(). Returns an object of
        // Color with given constant.
        // Uncommenting second line causes exception
        // IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}
Output :
RED at index 0
GREEN at index 1
BLUE at index 2
RED
enum and constructor :
 enum can contain constructor and it is executed separately for each enum constant
at the time of enum class loading.
 We can’t create enum objects explicitly and hence we can’t invoke enum constructor
directly.
enum and methods :
 enum can contain both concrete methods and abstract methods. If an enum class
has an abstract method, then each instance of the enum class must implement it

// Java program to demonstrate that enums can have constructor


// and concrete methods.
  
// An enum (Note enum keyword inplace of class keyword)
enum Color
{
    RED, GREEN, BLUE;
  
    // enum constructor called separately for each
    // constant
    private Color()
    {
        System.out.println("Constructor called for : " +
        this.toString());
    }
  
    public void colorInfo()
    {
        System.out.println("Universal Color");
    }
}
  
public class Test
{    
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}
Output:
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Design Pattern
https://www.tutorialspoint.com/design_pattern/design_pattern_overview.htm

Java Collections
https://www.edureka.co/blog/java-collections/

https://www.geeksforgeeks.org/collections-in-java-2/

https://www.javatpoint.com/collections-in-java

jvm memory
https://www.javatpoint.com/memory-management-in-java

https://www.geeksforgeeks.org/java-memory-management/

Object
https://www.tutorialspoint.com/java/java_object_classes.htm#:~:text=Object
%20%E2%88%92%20Objects%20have%20states%20and,object%20of%20its%20type%20support.

https://www.javatpoint.com/object-and-class-in-java

https://www.geeksforgeeks.org/classes-objects-java/

https://www.guru99.com/java-oops-class-objects.html

Thread
https://www.tutorialspoint.com/java/java_multithreading.htm

https://beginnersbook.com/2013/03/java-threads/

https://www.javatpoint.com/creating-thread

String Pool
https://www.journaldev.com/797/what-is-java-string-pool

https://www.edureka.co/blog/java-string-pool/

https://www.baeldung.com/java-string-pool

Garbage Collection
https://www.geeksforgeeks.org/garbage-collection-java/

https://www.javatpoint.com/Garbage-Collection

You might also like