Unit 1.1 Oops
Unit 1.1 Oops
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
➔ What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
11.Distributed
12.Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
1. Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.
2. Java code can be executed on multiple platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
• Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
• Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that is
why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
• Java is distributed because it facilitates users to create distributed applications
in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Multi-threaded
• A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-
media, Web applications, etc.
Dynamic
• Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management
(garbage collection).
➔The Java Environment
We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is
a software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
➔Java Source File Structure
Java source file structure describes that the Java source code file must follow a
schema or structure.
A Java program has the following structure:
1. package statements: A package in Java is a mechanism to encapsulate a group
of classes, sub-packages, and interfaces.
2. import statements: The import statement is used to import a package, class, or
interface.
3. class definition: A class is a user-defined blueprint or prototype from which
objects are created, and it is a passive entity.
Important Points to keep in mind while working with Java Source File
1. Number of classes in a Java source file:
Java allows us to create any number of classes in a program/File. But out of all the
classes, at most, one of them can be declared as a public class. In simple words, the
program can contain either zero public class, or if there is a public class present, it
cannot be more than one.
2. Name of the Java source file:
Java allows us to name the Java source file with anything if there is not a single class
that is declared as public. But if there is a class that is declared as public, the name
of the Java source file must be the same as the public class name. The Java source
file extension must be .java.
3. Number of .class files in a Java source file:
The number of .class files generated is equal to the number of classes declared in the
Java program.
Implementation of a Java application program involves a following step. They
include:
1. Creating the program
2. Compiling the program
3. Running the program
// FileName : "HelloWorld.java".
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello, World");
}
}
• Compiling the program
C:/> javac HelloWorld.java
Upon successful compilation a Helloworld.class file will produced.
• Running the program
C:/> java HelloWorld
➔Java Identifiers
In programming languages, identifiers are used for identification purposes. In Java,
an identifier can be a class name, method name, variable name, or label.
For example : we have 5 identifiers namely :
There are certain rules for defining a valid java identifier. These rules must be
followed, otherwise we get compile-time error. The only allowed characters for
identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and
‘_‘ (underscore).For example “geek@” is not a valid java identifier as it contain ‘@’
special character.
• Identifiers should not start with digits([0-9]). For example “123geeks” is a not
a valid java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier. For example “int while = 20;”
is an invalid statement as while is a reserved word. There are 53 reserved
words in Java.
• Examples of valid identifiers :
Main Method
Whether the class contains main() or not and whether the main() is properly declared
or not. These changes are not responsible of compiler.
At run time, JVM is responsible for these checking. If JVM unable to find required
main() then we will get run time exception saying NoSuchMethodError:main.
JVM always searches for main() method with the following signature.
public static void main(String[] args)
public --> To call by JVM from any where (Call from command line etc)
static --> Without existing object also JVM has to call this method
void --> Main method won't return anything to JVM
main --> Name of the method which is configured inside JVM
String[] args --> Command line arguments
The above syntax is very strict and if we perform any change then we will get
Runtime Exception saying NoSuchMethodError:main.
Even though above syntax is very strict the following changes are acceptable.
1. Instead of public static we can declare static public i.e., the order of modifier is
not important.
2. We can declare String[] in any acceptable form
main(String[] args)
main(String []args)
main(String args[])
3. Instead of args we can declare any Java valid identifier.
4. Instead of String[] we can take var arg String parameter
main(String... args)
5. main() can be declared with the following modifiers also
final
synchronized
Strictfp
public class Test
{
static final synchronized strictfp public void main(String... args)
{
System.out.println("Hi this is Java");
}
}
Inheritance concept is applicable for static methods including main() also.
Hence if the child class doesn’t contain main() then parent class main() will be
executed.
Example-1:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is Programming");
}
}
class Child extends Parent
{
}
javac Parent.java
java Parent
This is Programming
java Child
This is Programming
Example-2:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is OOPs");
}
}
class Child extends Parent
{
public static void main(String[] args)
{
System.out.println("This is Java");
}
}
It seems to be overriding concept is applicable for static methods, but it’s not
overriding but it is method hiding.
Overloading concept is applicable for main() but JVM always calls String[]
argument method only. The other method we have to call explicitly.
Example:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is OOPs");
}
public static void main(int[] args)
{
System.out.println("This is Java");
}
}
javac Parent.java
java Parent
This is OOPs
Class Modifiers
Whenever we are writing our own java class compulsory we have to provide some
information about our class to the JVM like,
▪ But for the inner classes the following modifiers are allowed
1. public
2. <default>
3. final
4. abstract
5. strictfp
6. private
7. protected
8. static
public classes
If a class declared as the public then we can access that class from any where
package pack1;
public class A {
public void m1() {
System.out.println("Hai this is Java");
}
}
package pack2;
import pack1.A;
class B {
public static void main() {
A a = new A();
a.m1();
}
}
If we are not declaring class A as public then we will get compile time error while
compiling B class, saying pack1.A is not public in pack1 can’t be accessed from
outside package.
default classes
▪ If a class declared as default then we can access that class only with in that
current package i.e., from outside of the package we can’t access..
▪ If you don’t use any modifier, it is treated as default by default.
package pack1;
class A{
void msg(){
System.out.println("Hello This is Java");
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String args[]){
A obj = new A();//C.E
obj.msg();//C.E
}
}
Final Modifier
Final Method
class P {
public void property() {
System.out.println("Money + Gold + Land");
}
public final void marry() {
System.out.println("Alekya");
}
}
class C extends P {
public void marry() {
System.out.println("Manasa");
}
}
Final Class
If a class declared as final we cannot extend functionality of that class i.e., we can’t
create child class for that class. i.e., inheritance is not possible for final classes.
final class P {
class C extends P {
}
C.E: cannot inherit from final P
Note:-
Every method present inside a final class is always final by default. But every
variable present inside final class need not be final.
abstract modifier
abstract is the modifier applicable for classes and methods but not for variables.
abstract method
E.g
Notes:-
srictfp modifier
▪ We can use strictfp for classes and methods but not for variables
▪ Usually the result of floating point arithmetic is varied from platform if we
want platform independent results for floating point arithmetic then we should
go for strictfp modifier
strictfp method
strictfp class
public members
If we declare a member as public then we can access that member from anywhere
but corresponding class should be visible (public) i.e., before checking member
visibility we have to check class visibility.
default members
If a member declared as the default, then we can access that member only with in
the current package and we cannot access from outside of the package. Hence,
default access is also known as package level access.
private members
▪ If a member declared as private then we can access that member only with in
the current class.
▪ abstract methods should be visible in child classes to provide implementation
where as private methods are not visible in child classes. Hence private-
abstract combination is illegal for methods.
protected members
If a member declared as protected then we can access that member with in the
current package any where but outside package only in child classes.
▪ With in the current package we can access protected members either by parent
reference or by child reference.
▪ But from outside package we can access protected members only by using
child reference. If we are trying to use parent reference then we will get
compile time error
final variables
▪ If the value if a variable is varied from object to object such type of variables
are called instance variables.
▪ For every object a separate copy of instance variables will be created.
▪ For the normal instance variables it is not required to perform initialization
explicitly. JVM will provide default values.
▪ If the instance variable declared as the final then compulsory we should
perform initialization whether we are using or not otherwise we will get
compile time error.
Rule
For the final instance variables, we should perform initialization before constructor
compilation i.e., the following are various places for this,
E.g
class Test {
▪ static is the modifier applicable for variables and methods but not for classes
▪ If the value of a variable is same for all objects then we should go for static
variables. In the case of static variable only one copy will be created at class
level and share that copy for every object of that class.
▪ static members can be accessed from both instance as well as class name.
▪ For static methods compulsory implementation should be available where as
for abstract methods implementation should not be available hence abstract
static combination is illegal for methods.
▪ Inheritance concept is applicable for static methods including main() method.
synchronized modifier
native modifier
▪ native is the modifier applicable for methods but not for variables and classes
▪ The native methods are implemented in some other languages like c and c++
hence native methods also known as foreign methods.
▪ The main objectives of native keyword are
1. To improve performance of the system.
2. To use already existing legacy non java code.
transient modifier
▪ transient is the modifier applicable only for variables and we cannot apply for
methods and classes.
▪ At the time of serialization, if we don’t want to save the value of a particular
variable to meet security, then we should go for transient keyword.
volatile modifier
▪ volatile is the modifier applicable only for variables but not for methods and
classes
▪ If the value of a variable keep on changing such type variables we have to
declare with volatile modifier.
▪ If a variable declared as volatile then for every thread a separate local copy
will be created.
▪ Every intermediate modification performed by that thread will takes place in
local copy instead of master copy.
▪ Once the value got finalized just before terminating the thread the master copy
value will be updated with local stable value.
➔Constructors in Java
Constructors in Java are special types of methods that are used to initialize the
objects of the class. Constructors are called at the time of object creation of the class.
▪ The name of the constructor and the name of the class must be the same.
▪ The only allowed modifiers for the constructors are public, private, protected,
. If we are using any other modifier, we will get C.E(Compiler Error).
▪ The return type is not allowed for the constructors even void also. If we r
declaring return type, then the compiler treats it as a method, and hence there
is no Compilation Error and RuntimeError.
It is legal but not recommended to have a method whose name is exactly the same
as the class name. Here it was treated as method.