OOP Questions&Answers

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

Difference between object and class

There are many differences between object and class. A list of differences between object and
class are given below:

No. Object Class

Class is a blueprint or
1) Object is an instance of a class. template from which objects
are created.

Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar
2)
keyboard, mouse, chair etc. objects.

3) Object is a physical entity. Class is a logical entity.

Class is declared using class


Object is created through new keyword mainly e.g.
4) keyword e.g.
Student s1=new Student();
class Student{}

5) Object is created many times as per requirement. Class is declared once.

Class doesn't allocated


6) Object allocates memory when it is created.
memory when it is created.

There are many ways to create object in java such as new There is only one way to
7) keyword, newInstance() method, clone() method, factory define class in java using class
method and deserialization. keyword.

Let's see some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

Why java is Object Oriend Programming Language ?


Java is not a pure Object oriented language, but so called a "Hybrid" language.
For any language to be pure object oriented it must follow these 6 points strictly...
1) It must have full support for Encapsulation and Abstraction
2) It must support Inheritance
3) It must support Polymorphism
4) All predefined types must be Objects
5) All user defined types must be Objects
6) Lastly, all operations performed on objects must be only through methods exposed at the
objects.
Now, java supports 1, 2, 3 & 5 but fails to support 4 & 6.

Short Answer - Yes.

Longer version ->

Java is about 99% Object oriented programming(OOP) language.

This is what I have heard a lot of Java programmers in my early days of learning Java say.

The very essential core of Java is that it’s designed to be an object oriented language. Let’s
look at the basic (and ritualistic) “hello world” program :

1. public class HelloWorld {

2. public static void main(String[] args) {

3. // Prints "Hello, World" in the terminal window.

4. System.out.println("Hello, World");

5. }

6. }

This requires you to create a class as a container for the program to start execution through
the main method. Everything else can be part of this class or from a few to large number of
related classes that follow the OOP concepts like encapsulation, inheritance, composition,
polymorphism etc.

However, the reason it is not completely Object oriented is because of the presence of types
boolean , byte , char , short , int , long , float and double. These are not objects and are
collectively called as Primitives.

It’s because of these primitives that Java is not 100% OO as they can be used to hold data and
manipulate them without creating objects for them. The probable reason that they exist is
because it’s convenient (and probably faster) to use such primitive data structures

There are four main OOP concepts in Java. These are:

 Abstraction. Abstraction means using simple things to represent complexity. We all


know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it. In Java, abstraction means simple things like objects, classes, and variables
represent more complex underlying code and data. This is important because it lets
avoid repeating the same work multiple times.
 Encapsulation. This is the practice of keeping fields within a class private, then
providing access to them via public methods. It’s a protective barrier that keeps the
data and code safe within the class itself. This way, we can re-use objects like code
components or variables without allowing open access to the data system-wide.
 Inheritance. This is a special feature of Object Oriented Programming in Java. It lets
programmers create new classes that share some of the attributes of existing classes.
This lets us build on previous work without reinventing the wheel.
 Polymorphism. This Java OOP concept lets programmers use the same word to mean
different things in different contexts. One form of polymorphism in Java is method
overloading. That’s when different meanings are implied by the code itself. The other
form is method overriding. That’s when the different meanings are implied by the
values of the supplied variables. See more on this below.

Why java is platform independent??


Before understanding how Java is platform independent, you first need to know,

1. What is platform?
2. How C/C++ program is executed?
3. Difference between byte code and native code?
4. How Java program is executed?

Now, platform is combination of processor and OS(operating system). In general i can say
the hardware or software component in which programs run.

When you write program in C/C++ and when you compile it, it is directly converted into
machine readable language(.exe). This .exe file generated is specific to the operating system
i.e, when you compile program in windows OS, the .exe file generated for that program is
specific to only windows OS and cannot be made to run in UNIX OS.

Thats why C/C++ programs are platform dependent. Here .exe file is the Native code.

Native code is similar to machine code i.e codes that is understood by machine. Native codes
are specific to platform i.e, Native code generated by program for Windows OS is different
from Native code generated for the same program for Unix OS.
Byte codes are nothing but intermediate codes generated after compilation and it is not the
executable code like Native code. The Byte code requires a virtual machine to execute in
machine. Byte codes generated by one platform can be executed in another platform also.

When you write program in JAVA and when you compile it, a separate file is created for the
program compiled, this file(.class) is known as byte code of java. This byte code will not be
in executable stage. The main purpose of generating byte code for a program compiled is to
achieve platform independency that means this byte code generated in one platform can be
executed in another. The one which makes the byte code generated in Windows OS to be
executed in the UNIX OS is the JVM of UNIX platform. From this statement, you may have
understand that JVM is platform dependent and the byte code generated by Java program is
platform independent. The Byte code generated can run on any JVM irrespective of to which
platform the JVM belongs .Whatever the JVM in which the byte code runs the output remains
same.

Mutable vs Immutable Objects


Mutable Immutable
Fields can be changed after the object creation Fields cannot be changed after object creation
Generally provides a method to modify the Does not have any method to modify the field
field value value
Has Getter and Setter methods Has only Getter method
Example: StringBuilder, java.util.Date Example: String

How to create a Mutable class?

To create a mutable class in Java you have to make sure the following requirements are
satisfied:

1. Provide a method to modify the field values


2. Getter and Setter method
How to create an Immutable class?

To create an immutable class in Java you have to make sure the following requirements
are satisfied:

1. A class should be declared as final so that it can’t be extended.


2. All the fields should be made private so that direct access is not allowed
3. No setter methods
4. Make all mutable fields final, so that they can be assigned only once.

A mutable object can be changed after it's created, and an immutable object can't.

In Java, everything (except for strings) is mutable by default:

public class IntegerPair {


int x;
int y;

IntegerPair(int x, int y) {
this.x = x;
this.y = y;
}
}

IntegerPair p = new IntegerPair(5, 10);


// p.x = 5, p.y = 10

p.x = 50;
// p.x = 50, p.y = 10

There's no way to make existing objects immutable. Even if an object is declared final, its
fields can still be changed:

public class IntegerPair {


int x;
int y;

IntegerPair(int x, int y) {
this.x = x;
this.y = y;
}
}

final IntegerPair p = new IntegerPair(5, 10);


// p.x = 5, p.y = 10

p.x = 50;
// p.x = 50, p.y = 10

That said, if you're defining your own class, you can make its objects immutable by making
all fields final and private.

public class IntegerPair {


private final int x;
private final int y;

IntegerPair(int x, int y) {
this.x = x;
this.y = y;
}
}

IntegerPair p = new IntegerPair(5, 10);

p.x = 50;
// Compilation error: cannot assign a value to a final variable

Strings can be mutable or immutable depending on the language.

Strings are immutable in Java.

Any time you change a string (e.g.: tacking on an extra character, making it lowercase,
swapping two characters), you're actually creating a new and separate copy:

Example to understand immutable object much better!

An immutable object is a kind of object whose state cannot be modified once it is created and
mutable object can be modified after it’s creation.

We all know all the wrapper classes are immutable(Boolean, Byte, Character, Double, Float,
Integer, Long, Short, and String)

For example,

After creating String object if we try to modify it,every modification in String creates a new
String object.

Public class immute

public static void main(String[] args) {

String str = "JAVA";

System.out.println(str);

str.toLowerCase(); //modifying the immutable

System.out.println(str);

}
O/P:

JAVA

JAVA

Means the changes didn’t effected the immutable object

toLower() constructs the new string object “java” instead modifying the existed one as it is
immutable

Rewrite the above code like this

Public class immute{

public static void main(String[] args) {

String str = "JAVA";

System.out.println(str);

String str1 = str.toLowerCase();

System.out.println(str1);

O/P:

JAVA

java

So, Every modification on immutable object creates a new object rather than modifying the
existing one ,where as in mutable the existing object gets modified.

If you want your class as immutable ,make it as final and don’t provide any methods to
modify the fields(no setter methods)

You might also like