OOP's concept of oops in programing
OOP's concept of oops in programing
The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.
The library contains components for managing input, database programming, and
much much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that
contain all the classes that belong to the specified package.
If you find a class you want to use, for example, the Scanner class, which is used to
get user input, write the following code:
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
Output:
Enter username
Abc
Username is: Abc
import a Package
we used the Scanner class from the java.util package. This package also contains
date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:
The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package within
the same directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class
names.
When we compiled the package in the example above, a new folder was created, called
"mypack".
This is my package!
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
For example
javac -d . Simple.java
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
1. import package.*;
2. import package.classname;
3. fully qualified name.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
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.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
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.
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.
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
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.
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Syntax:
A method which is declared as abstract and does not have implementation is known as an abstract
method.
Output:
running safely
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
What is Diamond Problem in Java
In Java, the diamond problem is related to multiple inheritance. Sometimes it is also known
as the deadly diamond problem or deadly diamond of death. In this section, we will
learn what is the demand problem in Java and what is the solution to the diamond
problem.
The default method is similar to the abstract method. The only difference is that it is defined
inside the interfaces with the default implementation. We need not to override these methods.
Because they are already implementing these interfaces.
The advantage of interfaces is that it can have the same default methods with the same name
and signature in two different interfaces. It allows us to implement these two interfaces, from a
class. We must override the default methods explicitly with its interface name.
The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an ambiguity that
arises when two classes B and C inherit from A, and class D inherits from both B and C.
You can achieve multiple inheritance in Java, using the default methods (Java8) and
interfaces.
From Java8 on wards default methods are introduced in an interface. Unlike other
abstract methods these are the methods of an interface with a default
implementation. If you have default method in an interface, it is not mandatory to
override (provide body) it in the classes that are already implementing this interface.
You can have same default methods (same name and signature) in two different
interfaces and, from a class you can implement these two interfaces.
If you do so, you must override the default method from the class explicitly specifying
the default method along with its interface name.
interface MyInterface1{
interface MyInterface2{
MyInterface1.super.display();
//or,
MyInterface2.super.display();
obj.display();
}
Output:
import java.util.*;
interface Sample1 {
interface Sample2 {
@Override
obj.sum(18,92);
The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler
at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored, the programmer should take care of (handle) these exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
The try statement allows you to define a block of code to be tested for errors while it
is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The finally statement lets you execute code, after try...catch, regardless of the
result
The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityEx
ception, etc.
The Error class defines the exception or the problems that are not expected
to occur under normal circumstances by our program, example Memory error,
Hardware error, JVM error, etc
The Exception class represents the exceptions that can be handled by our
program, and our program can be recovered from this exception using try and
catch block
A Runtime exception is a sub-class of the exception class. The Exception of
these type represents exception that occur at the run time and which cannot
be tracked at the compile time. An excellent example of same is divide by
zero exception, or null pointer exception, etc
IO exception is generated during input and output operations
Interrupted exceptions in Java, is generated during multiple threading.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods
1
public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.
2
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3
public String toString()
Returns the name of the class concatenated with the result of getMessage().
4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output
stream.
5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method at
the bottom of the call stack.
6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Common Exceptions
In Java, it is possible to define two catergories of Exceptions and Errors.
JVM Exceptions − These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException.
Programmatic Exceptions − These exceptions are thrown explicitly by the application or the
API programmers. Examples: IllegalArgumentException, IllegalStateException.
Inheritance in java
The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance.
The aim of inheritance is to provide the reusability of code so that a class has to write
only the unique features and rest of the common properties and functionalities can be
extended from the another class.
Child Class:
The class that extends the features of another class is known as child class, sub class or
derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.
This means that the data members(instance variables) and methods of the parent class
can be used in the child class as.
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC
is parent class. The class XYZ is inheriting the properties and methods of ABC class.
Inheritance Example
class Teacher {
String designation = "Teacher";
String collegeName = "Book";
void does(){
System.out.println("Teaching");
}
}
Book
Teacher
Physics
Teaching
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends
the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class
extends the child class. For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same
class A.
Multiple Inheritance: refers to the concept of one class extending more than one
classes, which means a child class has two parent classes. For example class C extends
both classes A and B. Java doesn’t support multiple inheritance,
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :
Constructor of Parent
Constructor of Child
Child Method
Parent Method
Interface
An interface is just like Java Class, but it only has static constants and abstract method. Java uses
Interface to implement multiple inheritance. A Java class can implement multiple Java Interfaces. All
methods in an interface are implicitly public and abstract.
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.
interface <interface_name>
{
To use an interface in your class, append the keyword "implements" after your class name
followed by the interface name.
Class Interface
A Java class can implement multiple Java Interfaces. It is necessary that the class
must implement all the methods declared in the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning which classes
it belongs.
Class needs to provide functionality for the methods declared in the interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only one class
but implement any number of interfaces
An interface cannot implement another Interface. It has to extend another interface if
needed.
An interface which is declared inside another interface is referred as nested interface
At the time of declaration, interface variable must be initialized. Otherwise, the
compiler will throw an error.
The class cannot implement two interfaces in java that have methods with same name
but different return type.
Summary:
The class which implements the interface needs to provide functionality for the
methods declared in the interface
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. A class can extend only one
class but implement any number of interfaces
// Example of interface
interface Pet{
p.test();
Output:
Output: Hello
Welcome
Java Threading
Java is a multi-threaded programming language which means we can develop multi-threaded program
using Java. A multi-threaded program contains two or more parts that can run concurrently and each
part can handle a different task at the same time making optimal use of the available resources
specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide
specific operations within a single application into individual threads. Each of the threads can run in
parallel. The OS divides processing time not only among different applications, but also among each
thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the
same program.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a
constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and are very much platform dependent.
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method
provides an entry point for the thread and you will put your complete business logic inside this method.
Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is
the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run(
) method. Following is a simple syntax of start() method −
void start();
// Example of multithreading
class RunnableDemo implements Runnable {
private Thread t;
threadName = name;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
if (t == null) {
t.start ();
R1.start();
R2.start();
Output:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Threading Questions
Multithreading and Synchronization are considered as the typical chapter in java
programming. In game development companies, multithreading related interview
questions are asked mostly. A list of frequently asked java multithreading and
concurrency interview questions is given below.
1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Multithreading is
used to obtain the multitasking. It consumes less memory and gives the fast and efficient
performance. Its main advantages are:
1. New: In this state, a Thread class object is created using a new operator, but the
thread is not alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method.
However, the thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state,
and the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is
waiting for the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run()
method exits.
However, the primary differences between both the ways are given below:
o By extending the Thread class, we cannot extend any other class, as Java does not
allow multiple inheritances while implementing the Runnable interface; we can also
extend other base class(if required).
o By extending the Thread class, each of thread creates the unique object and
associates with it while implementing the Runnable interface; multiple threads
share the same object
o Thread class provides various inbuilt methods such as getPriority(), isAlive and
many more while the Runnable interface provides a single method, i.e., run().
Syntax:
When we call the sleep() method, it pauses the execution of the current thread for the
given time and gives priority to another thread(if available). Moreover, when the waiting
time completed then again previous thread changes its state from waiting to runnable and
comes in running state, and the whole process works so on till the execution doesn't
complete.
1) The wait() method is defined in Object The sleep() method is defined in Thread
class. class.
2) The wait() method releases the lock. The sleep() method doesn't release the
lock.
When the multiple threads try to do the same task, there is a possibility of an
erroneous result, hence to remove this issue, Java uses the process of synchronization
which allows only one thread to be executed at a time. Synchronization can be achieved
in three ways:
o Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock
occurs when we provide locks to various threads so we should give one lock to only
one thread at some particular time.
o Avoid unnecessary locks: we must avoid the locks which are not required.
o Using thread join: Thread join helps to wait for a thread until another thread
doesn't finish its execution so we can avoid deadlock by maximum use of join
method.
Java thread scheduler also works for deciding the following for a thread:
o Synchronization
o Using Volatile keyword
o Using a lock based mechanism
o Use of atomic wrapper classes
o Executor
o FarkJoinPool
o ExecutorService
o ScheduledExecutorService
o Future
o TimeUnit(Enum)
o CountDownLatch
o CyclicBarrier
o Semaphore
o ThreadFactory
o BlockingQueue
o DelayQueue
o Locks
o Phaser
35) What is the Executor interface in Concurrency API in
Java?
The Executor Interface provided by the package java.util.concurrent is the simple
interface used to execute the new task. The execute() method of Executor interface is
used to execute some given command.
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.
The key benefit of overriding is the ability to define method that's specific
to a particular subclass type.
1. Method name must be same for both parent and child classes.
2. Access modifier of child method must not restrictive than parent class
method.
3. Private, final and static methods cannot be overridden.
4. There must be an IS-A relationship between classes (inheritance).
In Java, Method Overloading is not possible by changing the return type of the method
only.
Output:
Dog like to eat meat
As you can see here Dog class gives it own implementation of eat() method. For method
overriding, the method must have same name and same type signature in both parent and
child class.
NOTE: Static methods cannot be overridden because, a static method is bounded with
class where as instance method is bounded with object.
be same.
Compile time
Runtime polymorphism.
polymorphism.
Increase readability of
Increase reusability of code.
code.
It is Compiled Time
It is Run Time Polymorphism.
Polymorphism.
It is performed between
two classes using It requires always inheritance.
inheritance relation.
different signature.
It is code refinement
It is a code replacement technique.
technique.
No keywords are used Virtual keyword is used in the base class and
while defining the method. overrides keyword is used in the derived class.
No restriction is Throws
Restriction in only checked exception.
Clause.
It is also known as
Compile time
polymorphism or static
It is also known as Run time polymorphism or
polymorphism or early
Dynamic polymorphism or Late binding
binding
Example
Example:
class
OverloadingDemo{
class Demo2{
static int add1(int
x,int y){return void a()
x+y;}
{System.out.println("A");}}
static int add1(int
x,int y,int class b extends c
z){return x+y+z;}
{void a(){System.out.println("B");}
}
Que. Can we Override static method? Explain with reasons?
Upcasting in Java
class Game
{
public void type()
{
System.out.println("Indoor & outdoor");
}
}
this keyword
In Java, this is a keyword which is used to refer current object of a class.
we can it to refer any member of the class. It means we can access any
instance variable and method by using this keyword.
The main purpose of using this keyword is to solve the confusion when we
have same variable name for instance and local variables.
We can use this keyword for the following purpose.
class Demo
this.width = w;
this.height = h;
this.depth = d;
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}
Output:
width = 10.0
height = 20.0
depth = 30.0
class Demo
System.out.println("Welcome");
this.getName();
}
d.display();
Output:
Welcome
class Demo
{
public void getName()
{
System.out.println("Welcome");
}
Welcome
/*
<applet code="RadioButtonExample.class" width="500"
height="500">
</applet>
*/---------------------------------------------------------------------