1. Introduction to Object Oriented Programming Concepts in Java
- Object Oriented Programming is used to represent the real world data.
- The main focus is on data.
- Simula is considered to be the first object oriented programming language.
Object Oriented Programming Concepts
There are 6 object oriented programming concepts in Java which are given below.
- Class
- Object
- Encapsulation
- Polymorphism
- Inheritance
- Abstraction
Class
The Class is a collection of similar type of objects which have some common properties.
Object
The Object is any real world entity which have physical existence either living or non-living.
Encapsulation
The wrapping up of data and functions into a single unit (class) is known as encapsulation like this pictures
Polymorphism
Inheritance
Abstraction
Hiding the complexity and showing the functionality is known as abstraction.
Showing the essential data and hiding the non essential data or rather show only relevant information and to simplify it by comparing to something similar in the real world.
Class
- Class is the collection of similar type of objects which have some common properties.
- Class is a concept which is implemented by object.
- Class is a blueprint of java program from which we create object, then object is instance of class.
- We can also say that class is a collection of variables and methods.
Class
{
Methods: Represent Property
Variables: Represent Behavior
}
Object
- Any real world entity which have physical existence either living or non living is called an object.
- It is a runtime memory area. Object goes to heap.
How to Create an Object?
- In Java object of any class is created using new keyword.
- new keyword reserve the memory for an object in heap and generate an implicit reference id which is stored in a reference variable.
class Emp
{
String name;
int salary;
void get(String n1,int s1)
{
name=n1;
salary=s1;
}
void show()
{
System.out.println(name);
System.out.println(salary);
}
public static void main(String...s)
{
Emp e1=new Emp();
e1.get("aa",101);
e1.show();
new Emp().get("bb",102); //Anonymous Object
new Emp().show(); //Anonymous Object
}
- In above example total three objects are created. Firstly an object is created
using new operator and its reference id is stored in reference variable e1.
Then using e1 we call get() and show() methods. After that we are creating
two anonymous objects. You can see that we are getting different outputs
in three objects. - Anonymous object is an object without name.
- We can store one reference id into more than one reference variable.
Example: Emp e1=new Emp();
Emp e2=e1;
Simple
- Java derives its syntax from C and object oriented features from C++.
- If you are good in C and C++ programming then you can learn Java easily.
Hence Java is Simple.
Secure
- Java provides its own execution environment and hence do not allow any malicious program to access other parts of computer.
- Java Virtual Machine (JVM) verifies the code before execution (sandbox security).
Portable
- Java is platform independent i.e. Write Once and Run Anywhere (WORA).
- When java program is compiled a .class file (bytecode) is created. This .class file
can run on any platform (linux, windows, mac). You just need JVM of that platform.
Robust
Java is called as robust because of following two features:
- Automatic Memory Management
- Automatic Exception Handling
Object-Oriented
- Java is object oriented programming language same as C++.
- It means focus on the data and methods that manipulate that data instead of taking care of procedures.
Multithreaded
- Java supports multithreaded programming.
- It allows you to write programs that do many things simultaneously.
Architecture-Neutral
- Java is machine independent.
- It was made with goal “write once; run anywhere, anytime, forever”.
Interpreted
- Java enables the creation of cross-platform program i.e. bytecode.
- This code can be executed on any platform that has JVM.
High Performance
- Java bytecode can be easily executed on any machine for very high performance by using a just-in-time (JIT) compiler.
Dynamic
- Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time.
Distributed
- Java enables the creation of distributed applications which can be accessed on the internet.
Image Source: http://www.javatpoint.com/features-of-java
class demo
{
int x=10;
void show(int x,demo d1)
{
System.out.println(this.x);
System.out.println(d1.x);
System.out.println(x);
}
public static void main(String...s)
{
demo d1=new demo();
d1.show(20,d1);
}
}
Output:
10
10
20
- In Java by default this is passed to all non static methods.
- this cannot be used into static methods.
- this is the reference variable or local variable, it goes to stack.
- When local and global variables are same then this situation is known as data shadowing. In such situation this keyword is used to distinguish between local and global variable.
Consider below example:
class demo
{
int x=10;
void show()
{
int x=20;
System.out.println(this.x); //golabal variable
System.out.println(x); //local variable, priority goes to local variable
}
public static void main(String...s)
{
demo d=new demo();
d.show();
}
}
Output
10
20
Watch below video tutorial to understand this keyword easily
Watch below video tutorial to understand this keyword easily
4. Polymorphism in Java
- Polymorphism is used to assume the ability of several different forms. Or
we can say performing one task in different ways. - In java + operator is used for addition as well to concatenate (join) strings.
Here a single operator is doing two different things depending upon the
type of argument, so it is the situation of polymorphism.
Types of Polymorphism
Compile Time Polymorphism
- When functionality of an object bound at compile time, it is known as compile time polymorphism.
- Compile time polymorphism is of two types, operator overloading and method overloading.
- Java doesn't support operator overloading, it only support method overloading.
Note: It is given in java language specification that java doesn’t support compile time polymorphism, method overloading is also supported at method overriding.
Runtime Polymorphism
- When functionality of an object bound at runtime, it is known as runtime polymorphism.
- Method overriding is the example of runtime polymorphism.
Method Overloading
Whenever we keep more than one method of same name but different in prototype in a class, it is known as method overloading.
Method overloading is achieved when:
1. Number of arguments are different
void show(int a);
void show(int a, int b);
2. Number of arguments same but different in data type
void show(int a);
void show(float a);
void show(long a);
A program to show method overloading is given below.
class demo
{
void show(int a)
{
System.out.println("int");
}
void show(float a)
{
System.out.println("float");
}
void show(long a)
{
System.out.println("long");
}
public static void main(String...s)
{
demo d = new demo();
d.show(10);
d.show(10.0F);
d.show(10L);
}
}
Method Overriding
Whenever parent and child class have same method, it is known as method overriding.
class base
{
void show()
{
System.out.println("base");
}
}
class child extends base
{
void show()
{
System.out.println("child");
}
public static void main(String...s)
{
child c=new child();
c.show();
}
}
If you have any doubt in above tutorial then you can ask your question.
- Constructor is a special method which is used to initialize the state of an object.
- Constructor is special method because it has following properties:
- Automatically called
- Constructor name is same as class name
- No return type
- Programmer can’t call constructor explicitly. It is called automatically at the time of creation of object.
- Constructor implicitly returns this (reference of current object)
Types of Constructor
Default Constructor
Default constructor does not take any argument and it is used to initialize default values of an object.
Source:
class A
{ A() //default constructor { System.out.println("default constructor"); } public static void main(String...s) { new A(); } }
Parameterized Constructor
Constructor having one or more arguments is called parameterized constructor. Example of parameterized constructor is given below.
Source:
class A
{ A(int x) { System.out.println(x); } public static void main(String...s) { new A(10); } }
Copy Constructor
Copy constructor is a type of parameterized constructor. It is used to copy existing object values into another object at its creation time.
Source:
Source:
class temp { int x,y; temp(int x,int y) //parameterized constructor { this.x=x; this.y=y; } temp(temp t) //copy or parameterized constructor { this.x=t.x; this.y=t.y; } void show() { System.out.println(x); System.out.println(y); } public static void main(String...s) { temp t1=new temp(10,20); t1.show(); temp t2=new temp(t1); t2.show(); } }
- In java each class has constructor. If we do not write any constructor in our class
then compiler will add a default constructor implicitly. This can be proved by decompiling the .class file as shown below.
- Constructor can be overloaded same as like method overloading.
- Constructor can be private but can’t be final (constant).
Source:
class temp { temp() { System.out.println("constructor"); } void temp() { System.out.println("function"); } public static void main(String...s) { new temp(); new temp().temp(); } }
In above program we have used temp() two times. Have you thought how compiler differentiate between temp() and void temp()? It is done by their positions, the first temp() is treated as constructor while the next temp() is treated as method.
Constructor Chaining
Calling one constructor form another constructor is known as constructor chaining. Below program shows the concept of constructor chaining.
Source:
Source:
class temp { temp() { this(10); System.out.println("default"); } temp(int x) { this(10,20); System.out.println(x); } temp(int x,int y) { System.out.println(x+" "+y); } public static void main(String...s) { new temp(); } }
Rules:
- this can’t be used into normal method to call constructor.
- this must be first line of constructor.
- We can use constructor chaining only when object is created using new keyword.
- Order of calling doesn't matter.
Before understanding autoboxing and unboxing in java we must know what is wrapper class. So lets take a look on it.
Wrapper Class
A wrapper class wraps around a primitive data type and gives it an object appearance. This wrapper class object can be used whenever the primitive data type is required as an object.
Autoboxing in Java
The process of converting primitive data type into wrapper class object automatically is known as autoboxing. This feature was added from JDK 1.5.
The example for autoboxing is given below. Till JDK 1.4 we have to manually do the conversion of primitive data type into wrapper class and vice-versa using wrapper class method but from JDK 1.5 it is done automatically.
Till JDK 1.4
From JDK 1.5
Unboxing in Java
The process of converting wrapper class object into primitive data type automatically is called unboxing.
Till JDK 1.4
From JDK 1.5
A list of primitive data type with their corresponding wrapper class is given below.
Primitive Data Type
|
Wrapper Class
|
byte
|
Byte
|
short
|
Short
|
int
|
Integer
|
long
|
Long
|
float
|
Float
|
double
|
Double
|
char
|
Character
|
boolean
|
boolean
|
Video Tutorial to Explain Autoboxing and Unboxing in Java
If you found anything wrong or missing in above tutorial then please mention it by commenting below.
- Creating a new class from existing class is known as inheritance.
- Inheritance is used to achieve dynamic binding and reusability.
- The class which is inherited is known as super class or parent class and the class derived from the parent class is known as sub class or child class.
- Inheritance is implemented using extendskeyword. Just take a look on below syntax.
class parent_class_name extends child_class_name
{
//body
} - All the properties of parent class come to child class if they are not private.
- An example about how inheritance is implemented in java is given below.
class parent
{
String name="Mark";
}
class child extends parent
{
void show()
{
System.out.println(name);
}
public static void main(String...s)
{
child c=new child();
c.show();
}
}
- In above example variable name is default therefore it is accessible in child class. If we makename as private then it will show error like “name has private access in parent”.
Types of Inheritance in Java
- There are three types of inheritance in java: single, multilevel and hierarchical inheritance.
- In java, multiple inheritance is not supported by class. Multiple inheritance can be implemented by Interface, later on we will discuss about it.
Why multiple inheritance is not supported in java?
- In order to decrease the complexity and ambiguity, multiple inheritance is not supported in java.
- Consider a situation in which we have three classes A, B and C. Class C inherit class A and B. If classes A and B have a method with same prototype and when we call this method in class C then it will cause ambiguity because compiler will be confused that whether method from class A is called or method from class B is called.
Super refer to parent class. It holds the reference id of parent section of child class object. Observe below example.
class A
{
int x=10;
}
class B extends A
{
int x=20;
}
Here you can see that in child object, two separate sections are created namely parent section and child section. So super actually refer to parent section.
Use of Super Keyword in Java
There are three usage of super keyword in java.
- Access parent class instance variable.
- Invoke parent class method.
- Invoke parent class constructor.
Below program will show all the three usage of super keyword.
class parent { int x=20; parent() { System.out.println("Parent"); } void show() { System.out.println("Parent Show"); } } class child extends parent { int x=30; child() { super();//invoke parent constructor } void show() { System.out.println("Child Show"); } void display() { System.out.println(x); //print child x System.out.println(super.x); //print parent x show(); //invoke child show() super.show(); //invoke parent show() } public static void main(String...s) { child c=new child(); c.display(); } }
- Here both the classes have variable x and method show(). To access variable of child class we simply write x and to access variable of parent class we write super.x.
- Similarly, to invoke method of child we simple write show() and to invoke method of parent we write super.show(). In this way super is also used to remove the problem of method overriding.
- super() must be first line of the constructor. In above example we have written super() in first line of child class constructor to call parent class constructor.
- Super can’t be used in static method.
- By default super is first line of constructor. Super keyword and this keyword can’t be used together in constructor.
If you find anything wrong or missing in above tutorial then please mention it in
comment section.
comment section.
Very Good
ReplyDelete