Java Oops Concepts
Java Oops Concepts
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
programming language?
Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.
Object
A runtime entity that has state and behaviour is known as an object. For example: chair,
table, pen etc. It can be tengible or intengible (physical or logical).
An object has three characterstics:
state:represents the data of an object.
behaviour:represents the behaviour of an object.
identity:Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user, but is used internally by the JVM to identify
each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It
is used to write, so writing is its behaviour.
Object is an instance of a class.Class is a template or blueprint from which objects are
created.So object is the instance(result) of a class.
Class
A class is a group of objects that have common property. It is a template or blueprint from
which objects are created.
A class in java can
contain:
data
member
method
constructor
block
Instance variable
A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime
when object(instance) is created.That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose
behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory
at runtime.
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
Output:55
45
Naming convention
A naming convention is a rule to follow as you decide what to name your identifiers (e.g.
class, package, variable, method, etc.), but it is not mandatory to follow that is why it is
known as convention not rule.
Advantage:
By using standard Java naming conventions they make their code easier to read for
themselves and for other programmers. Readability of Java code is important because it
means less time is spent trying to figure out what the code does.
class name
Interface
name
method
name
variable
name
package
name
constants
name
A 03: Both C++ and Java use similar syntax and are Object Oriented, but:
Java does not support pointers. Pointers are inherently tricky to use and troublesome.
Java does not support multiple inheritances because itcauses more problems than it
solves. Instead Java
supports multiple interface inheritance, which allows an object to inherit many method
signatures from
different interfaces with the condition that the inheriting object must implement those
inherited methods. The
multiple interface inheritance also allows an object to behave polymorphicallyon those
methods. [Refer Q 8
and Q 10in Java section.]
Java does not support destructors but rather adds a finalize() method. Finalize methods
are invoked by the
garbage collector prior to reclaiming the memory occupied by the object, which has the
finalize() method. This
means you do not know when the objects are going to be finalized. Avoid using finalize()
method to
release non-memory resourceslike file handles, sockets, database connections etc
because Java has only
a finite number of these resources and you do not know when the garbage collection is
going to kick in to
release these resources through the finalize() method.
Java does not include structures or unions because the traditional data structures are
implemented as an
object oriented framework (Java collection framework Refer Q14, Q15in Java section).
Java 13
All the code in Java program is encapsulated within classes therefore Java does not have
global variables or
functions.
C++ requires explicit memory management, while Java includes automatic garbage
collection. [Refer Q32 in
Java section].
Q 04: Explain Java class loaders? Explain dynamic class loading? LF
A 04: Class loaders are hierarchical. Classes are introduced into the JVM as they are
referenced by name in a class that
is already runningin the JVM. So how is the very first class loaded? The very first class is
specially loaded with
the help of static main() method declared in your class. All the subsequently loaded
classes are loaded by the
classes, which are already loaded and running. A class loader creates a namespace. All
JVMs include at least one
class loader that is embedded within the JVM called the primordial (or bootstrap) class
loader. Now lets look at
non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders
to be used in place of
primordial class loader. Let us look at the class loaders created by the JVM.
CLASS LOADER reloadable? Explanation
Bootstrap
(primordial)
class MyClass {
public static void main(String args[]) {
Car c= new Car();
}
}
Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time. Let us lookat how to load classes dynamically.
Class.forName (String className); //static method which returns a Class
The above static method returns the class object associated with the class
name. The string classNamecan be supplied dynamically at run time. Unlike the
static loading, the dynamic loading will decide whether to load the class Caror
the class Jeep at runtime based on a properties file and/or other runtime
Java 14
conditions. Once the class is dynamically loaded the following method returns an
instance of the loaded class. Its just like creating a class object with no
arguments.
class.newInstance (); //A non-static method, which creates an instance of a
class (i.e. creates an object).
Jeep myJeep = null ;
//myClassName should be read from a properties file or Constants interface.
//stay away from hard coding values in your program. CO
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);
A NoClassDefFoundException is
thrown if a class is referenced with
Javas newoperator (i.e. static loading)
but the runtime system cannot find the
referenced class.
A ClassNotFoundException is thrown when an application tries to load in a
class through its string name using the following methods but no definition for the
class with the specified name could be found:
The forName(..) method in class - Class.
The findSystemClass(..) method in class - ClassLoader.
The loadClass(..) method in class - ClassLoader.
What are static initializers or static blocks with no function names? When a class is
loaded, all blocks
that are declared static anddont have function name (i.e. static initializers) are executed
even before the
constructors are executed. As the name suggests they are typically used to initialize
static fields. CO
public class StaticInitilaizer {
public static finalint A = 5;
public static finalint B;
//Static initializer block, which is executed only once when the class is loaded.
static{
if(A == 5)
B = 10;
else
B = 5;
}
public StaticInitilaizer(){} // constructor is called only after static initializer block
}
The following code gives an Output of A=5, B=10.
public class Test {
System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B);
}
Q 05: What are the advantages of Object Oriented Programming Languages (OOPL)?DC
A 05: The Object Oriented Programming Languages directly represent the real life objects
like Car, Jeep, Account,
Customeretc. The featuresof the OO programming languages like polymorphism,
inheritanceand
encapsulationmake it powerful. [Tip:remember pie which, stands forPolymorphism,
Inheritance and
Encapsulation are the3 pillars of OOPL]
Q 06: How does the Object Oriented approach improve software development? DC
A 06: The key benefits are:
Re-useof previous work: using implementation inheritance and object composition.
Real mapping to the problem domain:Objects map to real world and represent vehicles,
customers,
products etc: with encapsulation.
Modular Architecture:Objects, systems, frameworks etc are the building blocks oflarger
systems.
Java 15
The increased quality and reduced development time are the by-products of the key
benefits discussed above.
If 90% of the new application consists of proven existing components then only the
remaining 10% of the code
have to be tested from scratch.