You are on page 1of 11

Object Oriented Programming

What is OOP?
The object oriented programming is commonly known as OOP. Most of the languages are
developed using OOP concept. Object-oriented programming (OOP) is a programming concept
that uses "objects" to develop a system.
A programming object has an ability to perform actions and has attributes. It performs just like
real world entities for e.g. a motor bike. A bike performs actions such as 'Start', 'Stop' etc., and it
has attributes like red color, 150 cc etc. So does an Object. Actions and attributes are
represented by Methods and fields or properties respectively in programming language.
An object hides the implementation details and exposes only the functionalities and parameters it
requires to its client. Here also an object shares the same concept as that of a bike. While driving
a motor bike, we are unaware of its implementation details such as how it is developed, internal
working of gears etc. We know only the functions or actions it can perform.
What are the various elements of OOP?
Various elements of OOP are:
Object

Class

Method

Encapsulation

Information Hiding

Inheritance

Polymorphism

Explain an object.
An object is an entity that keeps together state and behaviors. For instance, a car encapsulates
state such as red color, 900 cc etc and behaviors as 'Start', 'Stop' etc., so does an object.
An object is an instance of a class. If you consider Dog as a class, it will contain all possible dog
traits, while object German Shepherd contains characteristics of specific type of dog.
Define a class.
A class represents description of objects that share same attributes and actions. It defines the
characteristics of the objects such as attributes and actions or behaviors. It is the blue print that
describes objects.
What is Method?
Method is an objects behavior. If you consider Dog as an object then its behaviors are bark,
walk, run etc.

Explain Encapsulation concept in OOP.


Encapsulation means keeping actions and attributes together under a single unit. This can also
be understood using a motor bike example. A bike has actions such as 'switch on light', 'horn' etc.
and attributes such specific color, size, weight etc. Here the actions and attributes are bundled
together under a single unit, bike.

In a programming language, methods and properties that correspond to actions and attributes
respectively are kept under a unit called object. The advantage of encapsulation is that the
implementation is not accessible to the client. The user has to know only the functionality of
encapsulated unit and information to be supplied to get the result.
What is Information Hiding in OOP?
Information hiding concept restricts direct exposure of data. Data is accessed indirectly using safe
mechanism, methods in case of programming object. Taking bike as an example, we have no
access to the piston directly, we can use 'start button' to run the piston. You can understand the
advantage of information hiding concept from this example. If a bike manufacturer allows direct
access to piston, it would be very difficult to control actions on the piston.
Define Inheritance.
Inheritance concept in OOP allows us to create a new class using an existing one. It also allows
the new class to add its own functionality. This concept can also be related to real world entity. A
bike manufacturer uses same mechanism of existing version of the bike while launching a new
version with some added functionalities. This allows him to save time and efforts.
Explain the term Polymorphism.
Polymorphism means the ability to take more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends on the data types used in the operation.
What is Overloading Polymorphism?
Overloading allows multiple functions to exist with same name but different parameters. Again if
you take bike as an example, it has a function Start with two forms i.e. 'Auto Start' and 'kick
start'.
Explain Overriding Polymorphism.
Overriding means changing behavior of methods of base class in derive class by overriding the
base class methods. If class A is a base class with method 'calculate' and class B inherits class A,
thus derives method 'calculate' of class A. The behavior of 'calculate' in class B can be changed
by overriding it.
What are the advantages of OOP?
Following are the advantages of OOP:

It presents a simple, clear and easy to maintain structure.

It enhances program modularity since each object exists independently.

New features can be easily added without disturbing the existing one.

Objects can be reused in other program.

Can you give some examples of tokens?


Some of the examples of tokens are:
- Keywords,
- Identifiers,
- Constants,
- Operators,
- Brackets,
- Commas.
What is friend function?

- Friend function is a friend of a class.


- It is allowed to access Public, private or protected data of that class.
- It can be declared anywhere in the class declaration
- It doesnt have any effect of access control keywords like private, public or protected.

Define Modularity?
- It is the property of big a system divided into small modules which can be integrated as per the
requirement.

Explain: a.) Static binding b.) Dynamic binding


a.) Static bindingIt is a binding in which the name of the class can be associated with it during compilation. Also
referred to as early binding.
b.) Dynamic binding
It is a binding in which the name of the class can be associated with it during execution time. Also
referred to as late binding.
What is inheritance?
inheritance is one of the oops concepts in java.inheritance is concept of getting properties of one
class object to another class object.
Inheritance represents the IS-A relationship,also known as parent-child relationship.
what are the types of inheritance?
1.Multiple inheritance( java doesn't support multiple inheritance).
2.Multilevel inheritance.
How Inheritance can be implemented in java?
Inheritance can be implemented in JAVA using below two keywords:
1.extends
2.implements
extends is used for developing inheritance between two classes and two interfaces.
implements keyword is used to developed inheritance between interface and class.
Why we need to use Inheritance?
1.For Code Re usability.
2.For Method Overriding.

what is syntax of inheritance?


public class subclass extends superclass{
//all methods and variables declare here
}

what is multilevel inheritance?


Getting the properties from one class object to another class object level wise with different
priorities.
what is Multiple inheritance?why Java Doesn't Support multiple Inheritance.
The concept of Getting the properties from multiple class objects to sub class object with same
priorities is known as multiple inheritance.
In multiple inheritance there is every chance of multiple properties of multiple objects with the
same name available to the sub class object with same priorities leads for the ambiguity. also
known as diamond problem. one class extending two super classes.
Because of multiple inheritance there is chance of the root object getting created more than
once.
Always the root object i.e object of object class hast to be created only once.
Because of above mentioned reasons multiple inheritance would not be supported by
java.Thus in java a class can not extend more than one class simultaneously. At most a class
can extend only one class.
How do you implement multiple inheritance in java?
Using interfaces java can support multiple inheritance concept in java. in java can not extend
more than one classes, but a class can implement more than one interfaces.
Program:
interface A{
}
interface B{
}
class C extends interface A,B{
}
Can a class extend itself?
No,A class can't extend itself.
What happens if super class and sub class having same field name?
Super class field will be hidden in the sub class. You can access hidden super class field in sub
class using super keyword.
Explain System.out.println()?
System is a class Which is present in java.lang package.
Out is a static final field (variable) of Printstream class
Println(): method of Printstream Class
Class System{
public static final Printstream Out;
}
Class Printstream{
public void println(){}}
Can you define an abstract class without any abstract methods?
1. yes.
2. Declaring a class abstract without abstract methods means that you don't allow it to be
instantiated on its own.
3. The abstract class used in java signifies that you can't create an object of the class
directly.

4. This will work:


public abstract class abs {
protected int s=0;
public void display() {
System.out.print("hello");
}
}

what are the differences between Final , finally finalize()?


final:
Any variable declare along with final modifier then those variables treated as final
variables
if we declare final variables along with static will became constants.
public final String name = "foo"; //never change this value
If you declare method as final that method also known as final methods.Final methods
are not overridden.means we can't overridden that method in anyway.
public final void add(){
}
public class A{
void add(){
//Can't override
}
}

If you declare class is final that class is also known as final classes.Final classes are not
extended.means we can't extens that calss in anyway.

public final class indhu{


}
public class classNotAllowed extends indhu {...} //not allowed
Finally:
Finally blocks are followed by try or catch.finally blocks are complasary executable blocks.But finally
is useful for more than just exception handling.
it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
continue, or break,Closing streams, network connection, database connection. Putting cleanup
code in a finally block is always a good practice even when no exceptions are anticipated
where finally doesn't execute e.g. returning value from finally block, calling System.exit from try
block etc
finally block always execute, except in case of JVM dies i.e. calling System.exit() .
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
//here close the database connection and any return statements like that we have to write
}
Finalize():
finalize() is a method which is present in Java.lang.Object class.

Before an object is garbage collected, the garbage collector calls this finalize() of object.Any
unreferenced before destroying if that object having any connections with database or anything..It
will remove the connections and it will call finalize() of object.It will destroy the object.
If you want to Explicitly call this garbage collector you can use System.gc() or
Runtime.gc() objects are there from a long time the garbage collector will destroy that objects.
public void finalize() {
//free resources (e.g. un allocate memory)
super.finalize();
}
What is Exception? difference between Exception and Error? and types of Exceptions?
1. Exceptions are the objects representing the logical errors that occur at run time and makes
JVM enters into the state of "ambiguity".
2. The objects which are automatically created by the JVM for representing these run time
errors are known as Exceptions.
3. An Error is a subclass of Throwable that indicates serious problems that a reasonable
application should not try to catch. Most such errors are abnormal conditions.
4. few of the subclasses ofError.
5. AnnotationFormatError- Thrown when the annotation parser attempts to read an
annotation from a class file and determines that the annotation is malformed.
6. AssertionError- Thrown to indicate that an assertion has failed.
7. LinkageError- Subclasses of LinkageError indicate that a class has some dependency on
another class; however, the latter class has incompatibly changed after the compilation of
the former class.
8. VirtualMachineError- Thrown to indicate that the Java Virtual Machine is broken or has
run out of resources necessary for it to continue operating.
9. There are really three important subcategories ofThrowable:
10. Error- Something severe enough has gone wrong the most applications should crash
rather than try to handle the problem,
11. Unchecked Exception (akaRuntimeException) - Very often a programming error such as
aNullPointerExceptionor an illegal argument. Applications can sometimes handle or
recover from thisThrowablecategory -- or at least catch it at the Thread'srun()method, log
the complaint, and continue running.
12. Checked Exception (aka Everything else) - Applications are expected to be able to catch
and meaningfully do something with the rest, such
asFileNotFoundExceptionandTimeoutException.

Why Java does not supports multiple inheritance?


Inheritance:

The concept of getting properties of one class object to another class object is known as
inheritance.

Here properties means variable and methods.


Types of Inheritance:
1.
Multiple inheritance.
2.
Multilevel inheritance.
Multiple inheritance:
The concept of Getting the properties from multiple class objects to sub class object with
same priorities is known as multiple inheritance.
Java Doesn't Support multiple Inheritance.

Diamond problem:
In multiple inheritance there is every chance of multiple properties of multiple objects
with the same name available to the sub class object with same priorities leads for the
ambiguity.
1. //Multiple inheritance program
2. Class A{
3. }
4. Class B extends A{
5. public void show(){
6. }
7. }
8. Class C extends A{
9. public void show(){
10. }
11. }
12. Class D extends B,C{ // not supported by java leads to syntax error.
13. }
We have two classes B and c which are inheriting A class properties.
Here Class D inheriting B class and C class So properties present in those classes will be
available in java.
But both classes are in same level with same priority.
If we want to use show() method that leads to ambiguity
This is called diamond problem.
Because of multiple inheritance there is chance of the root object getting created more than
once.
Always the root object i.e object of object class hast to be created only once.
Because of above mentioned reasons multiple inheritance would not be supported by java.
Thus in java a class can not extend more than one class simultaneously. At most a class can
extend only one class.
So these are the reasons that java does not supports multiple inheritance.Even though having
this much reasons some people say and we also gets some doubts when we are using
interfaces. lets me clear this one also. our immediate question should be.

IsJava supports multiple inheritance using interfaces?


Interfaces have fully abstract functionality.
Means methods in interfaces by default public abstract methods so we need to implement these
methods in classes which are extending this interface.
1.
2.
3.
4.
5.
6.
7.
8.
9.

/Multiple inheritance program


interface A{
public void show();
}
interface B{
public void display();
}
Class C Implements A,B{
}

Here it seems we are achieving multiple inheritance by using interfaces. but we are not.
Syntactically it seems to multiple inheritance but the actual implementation of multiple
inheritance is not there. how can i say that? let me clear

Difference between interfaces and inheritance:in multiple inheritance


Inheritance means getting the properties from one class object to another class object.
Means if any class extending another class then the super class methods can be used in sub
classes happily.
But in interfaces the methods in interfaces are fully abstract so we need to provide functionlity in
our extended class and use it .seems both are opposite right? yes.
That is the reason we can say interfaces are only supports syntactical multiple inheritance
which is not implementation of multiple inheritance.
So finally java supports only syntax of multiple inheritance does not supports implementation of
multiple inheritance.
Inheritance is like debit and interface is like credit but interface has its own importance in other
concepts like server side programming

Difference between throw and throws in java


Throw:

throw keyword used to throw user defined exceptions.(we can throw predefined
exception too)
If we are having our own validations in our code we can use this throw keyword.
For Ex: BookNotFoundException, InvalidAgeException (user defined)
//Custom exception
1 package com.instanceofjavaforus;
2 public class InvalidAgeException extends Exception {
3
InvaidAgeException(String msg){
4
super(msg);
5
}
6 }
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package com.instanceofjavaforus;
public class ThrowDemo {
public boolean isValidForVote(int age){
try{
if(age<18){
throw new InvalidAgeException ("Invalid age for voting");
}
}catch(Exception e){
System.out.println(e);
}
return false;
}
public static void main(String agrs[]){
ThrowDemo obj= new ThrowDemo();
obj.isValidForVote(17);
}
}
We can throw predefined exceptions also

25 package com.instanceofjavaforus;
26 public class ThrowDemo {
27 public void method(){

28 try{
29
30 throw new NullPointerException("Invalid age for voting");
31 }
32 }catch(Exception e){
33 System.out.println(e);
1
}
2
}
3
public static void main(String agrs[]){
4
ThrowDemo obj= new ThrowDemo();
5
obj.method();
6
}
7 }
Like this we can throw checked exceptions and unchecked exceptions also. But throw keyword is
mainly used to throw used defined exceptions / custom exceptions.

Throws:
The functionality of throws keyword is only to explicitly to mention that the method is
proven transfer un handled exceptions to the calling place.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

package com.instanceofjavaforus;
public class ThrowSDemo {
public void method(int a,int b) Throws ArithmeticException{
inc c= a/b;
}
public static void main(String agrs[]){
ThrowDemo obj= new ThrowDemo();
try{
obj.method(1,0);
}catch(Exception e){
System.out.println(e);
}
}
}

Uses of throws keyword:


Using throws keyword we can explicitly provide the information about unhand-led
exceptions of the method to the end user, Java compiler, JVM.

Using throws keyword we can avoid try-catch with respect to the statements which are
proven to generate checked exceptions.

It us highly recommended not to avoid try-catch with respect to the statements which are
proven to generate exceptions in main method using throws keyword to the main() method.

Why StringBuffer Class not overriding Equals() method?


YES StringBuffer and StringBuilder classes not overriding equals()method and haschcode()
method.
Before discussing about why these classes are not overriding equas() and hashcode() methods lets
see the usage of overriding equals and hashcode() methods.
String class is overriding these equals() and hashcode() methods.
When we want to compare two strings we use equals method.
basically equals() method is defined in Object class and it will compares the references of two
objects if those two objects reference is same then its returns true.

And if equals() methods returns true on comparing two objects then their hashcode() must be same
this is the contract between equals() and hashcode().
What is an applet? How does applet differ from applications?
A program that a Java enabled browser can download and run is an Applet.
An applet is embedded in a web-page and runs in the browser context.
The java.applet.Applet class provides a standard interface between the applet and the browser
environment. Applets cannot perform actions such as reading/writing to the file system. Java
applications run standalone, outside the browser.
What are the attributes of Applet tags?
height: Defines height of applet
width: Defines width of applet
align: Defines the text alignment around the applet
alt: An alternate text to be displayed if the browser support applets but cannot run this applet
archive: A URL to the applet when it is stored in a Java Archive or ZIP file
code: A URL that points to the class of the applet
codebase: Indicates the base URL of the applet if the code attribute is relative
hspace: Defines the horizontal spacing around the applet
vspace: Defines the vertical spacing around the applet
name: Defines a name for an applet
object: Defines the resource name that contains a serialized representation of the applet
title: Display information in tool tip
Difference between throw and throws

The throw key word is used to explicitly throw an exception, while throws is utilized to handle
checked exceptions for re-intimating the compiler that exceptions are being handled. It is kind of
communicating to the compiler that an exception is expected to throw one or more checked
exceptions.

The throws need to be used in the methods definition and also while invoking the method that
raises checked exceptions.

Difference between an Abstract class and Interface

An abstract class can have both abstract and concrete methods whereas an interface can have
only method signatures.

An abstract class is to be extended by another class, where as an interface is to be implemented


in another class.

A class can extend only one abstract class, whereas a class can implement multiple interfaces.

By default, all the methods are abstract and public in interface, whereas in abstract class, the key
words public and abstract are to be explicitly specified in an abstract class.
Advantages and disadvantages of interfaces.
Advantages

Interfaces are mainly used to provide polymorphic behavior.


Interfaces function to break up the complex designs and clear the dependencies between
objects.

Disadvantages

Java interfaces are slower and more limited than other ones.
Interface should be used multiple number of times else there is hardly any use of having
them.

You might also like