Unit 3 - OOPs Concepts
Unit 3 - OOPs Concepts
OOP approach:-
- OOP uses classes and objects in their programs. A class is a module which itself contains data
and methods to achieve tasks.
- The main task is divided into several methods and they are represented as classes. Each class can
perform some tasks for which several methods are written in a class. This approach is called OOP
approach.
- Ex: C++, Java, Python
A class describes the properties and actions performed by its objects. So the properties (variables) and
actions (methods) in the class as:
class Person{
String name; //properties of a person-variables
int age;
//actions done by a person – methods
void talk()
{
//code
}
void sleep()
{
//code
}
}
class Person has two variables and two methods. This class method is stored in JVM’s method area.
When we want to use this class, we should create an object to the class as:
class Demo{
public static void main(String args[])
Object creation:
The class code along with method code is stored in ‘Method area’ of the JVM When an object is
created, the memory is allocated on heap, after creation of the object. JVM produced a unique reference
number for the object from the memory address of the object. This reference number is called hash code
num.
To know the Object reference number, we can use hashCode() method of Object class.
Example:
class Person{
String name;
int age;
void talk()
{
System.out.println("My name is :"+name);
System.out.println("My age is: "+age);
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
Example:
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
}
- A constructor does not return any value, not even void type.
- A constructor is automatically called and executed at the time of creating an object. While
creating an object, if nothing is passed to the object the default constructor is called and executed.
- If some values are places to the object, then the parameterized constructor is called.
- A constructor is called and executed only once per object.
class Demo{
//main is executed by JVM when my program will run
public static void main(String args[]){
//Create an Object x
Person x = new Person();
// x is not an object its a reference variable which holds the hashCode of the object (it is a
reference)
x.talk();
}
}
O/P: My name is RGUKT
My age is 10
private: Private members of class in not accessible anywhere in program these are only accessible within
the class. Private are also called class level access modifiers.
Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private data
obj.show(); //Compile Time Error, you can't access private methods
}
}
Output: Compile Time Error, you can't access private methods and data
public: Public members of any class are accessible anywhere in the program in the same class and
outside of class, within the same package and outside of the package. Public are also called universal
access modifiers.
Example
class Hello
{
public int a=20;
Developed by: S.Rajani, RGUKT Page 10
public void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}
Output
20
Hello Java
protected: Protected members of the class are accessible within the same class and another class of the
same package and also accessible in inherited class of another package. Protected are also called derived
level access modifiers.
In below the example we have created two packages pack1 and pack2. In pack1, class A is public so we
can access this class outside of pack1 but method show is declared as a protected so it is only accessible
outside of package pack1 only through inheritance.
Example
// save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
default: Default members of the class are accessible only within the same class and another class of the
same package. The default are also called package level access modifiers.
Example
//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java
package pack2;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
}
Output
Hello Java
Methods in Java:-
A method represents a group of statements that performs a task. Here the task represents a
calculation or processing of data or generating a report etc..
ex: sqrt() method
It calculates square root value and returns that value.
Method has two parts:
1. method header or method prototype
2. method body
1. Method header or method prototype:
It contains method name, method parameters and method return type.
Syntax:
return datatype methodname(parameter1, parameter2….)
2. Method body:
Method body consists a group of statements which contains logic to perform the task.
class Add{
int a;
int b;
Add()
{
a=10;
b=20;
}
void sum()//without parameter
{
int c=a+b;
System.out.println(c);//without return type
}
}
class test{
public static void main(String args[])
{
int a,b;
Add n = new Add();
n.sum();
}
}
2. with parameters and with return type
class Add{
int a;
int b;
Add()
{
a=10;
b=20;
}
int sum(int a, int b)//with parameters
{
int c=a+b;
return(c);//with return type
class Add{
int a;
int b;
Add()
{
a=10;
b=20;
}
int sum()//without parameters
{
int c=a+b;
return c;//with return type
}
}
class test{
public static void main(String args[])
{
int a,b;
Add n = new Add();
System.out.println(n.sum());
}
}
4. with parameters and without return type
class Add{
int a;
int b;
Add(int x,int y)
{
a=x;
b=y;
}
Static Methods:
- A static method is a method that doesn’t act upon instance variables of a class.
- A static method is declared by using the keyword static.
- A static methods are called using classname.methodname()
- The reason why static methods can’t act on instance variables in that the JVM first executes the
static methods and then only it creates the objects. Since the objects are not available at the time
of calling the static methods, the instance variables are also not available.
The static methods can be:
1. static variables
2. static methods
3. static block
1. static variables:-
- static variables in java is available which belongs to the class and initialized only once at the start
of the execution.
- It is a variable which belongs to the class and not to the object (instance).
- static variables initialized first, before the initialization of any instance variables.
- a single copy to be shared by all instance of a class.
- A static variable can be accessed directly by the class name and doesn’t need any object.
- Syntax: classname.varablename;
Example:
class Person{
int rollno;
String name;
static String branch="EEE";
Person(int n,String s){
rollno=n;
name=s;
}
Developed by: S.Rajani, RGUKT Page 15
void display(){
System.out.println(rollno+""+name+""+branch);
}
}
class Person_Demo{
public static void main(String args[]){
Person p=new Person(1001,"RGUKT");
p.display();
System.out.println(Person.branch);//EEE
}
}
O/P: 1001 RGUKT EEE
EEE
2. static methods:
- static method in java is a method which belongs to the class and not the object. A static method
can access only static data.
- It can’t access non static data.
- A static method can be accessed directly by the class name and doesn’t need any object.
- A static method can’t refer ‘this’ and ‘super’ keywords.
- Syntax:classname.methodname();
Example:
class Test{
static int count=10;
static void access(){
System.out.println(count);
}
public static void main(String args[]){
Test.access();
}}
O/P: 55
Difference between instance variables and class variables:-
- An instance variable is a variable whose separate copy is available to each objects
- A class variable is a variable whose single copy in memory is shared by all objects
- Instance variables are created in the objects on heap memory.
- Class variables (static variables) are stored on method area.
3. static block:-
A static block is block of statements declared as static.
Syntax:
static{
//code
}
Developed by: S.Rajani, RGUKT Page 16
- JVM executes a static block on a highest priority basis. This means JVM first goes to static block
even before it looks for main() method in a program.
Example:
class Test{
static{
System.out.println("static block");
}
public static void main(String args[]){
System.out.println("main block");
}}
O/P: static block
main block
Example:
class Test
{
// static variable
static int a = 10;
static int b;
//static method
static int mul()
{
return a*b;
}
// static block
static {
System.out.println("Static block initialized.");
b = a + 4;
}
}
class StaticDemo{
public static void main(String[] args)
{
//Test m=new Test();
System.out.println("from main");
System.out.println("Value of a : "+Test.a);
System.out.println("Value of b : "+Test.b);
System.out.println("Multiplication of a&b : "+Test.mul());
}
}
output
Developed by: S.Rajani, RGUKT Page 17
from main
Static block initialized.
Value of a : 10
Value of b : 14
Multiplication of a&b : 140
This keyword:
this is a reference variable that refers to the current object. It is a keyword in java language
represents current class object.
Usage of this keyword
It can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
It can be used to invoke current class method (implicitly)
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.
Employee(int i,String n)
{
id = i;
name = n;
}
void show()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"rgukt");
Employee e2 = new Employee(112,"iiit");
e1.show();
e2.show();
}
}
Output
111 rgukt
112 iiit
In the above example, no need of use this keyword because parameter (formal arguments) and
instance variables are different. This keyword is only use when parameter (formal arguments) and
instance variables are same.
}
}
Output
before change 50
after change 50
passing by Object
As the name indicates, in this case we pass the memory reference or the object(also known as the
instance of the class to a function. In this method the values of the actual parameters are affected with
every change in the formal parameters.
Example
class Operation{
int data=50;
}
}
Output
before change 50
after change 150
Recursion:
A method calling itself is known as ‘recursion method’ and it is called as recursion.
Ex:
INHERITANCE
Inheritance is the process of taking the features (data members + methods) from one class to
another class.
The class which is giving the features is known as base/Parent class.
The class which is taking the features is known as derived / child class.
The subclass inherits all of its instances variables and methods defined by the superclass and it
also adds its own unique elements. Thus we can say that subclass is specialized version of
superclass.
Advantages:
1. Application development time is very less.
2. Redundancy (repetition) of the code is reducing. Hence we can get less memory cost and
consistent results.
3. Instrument cost towards the project is reduced.
4. Reusability of code.
5. Code sharing.
Syntax of Inheritance
class Subclass-Name extends Superclass-Name
Developed by: S.Rajani, RGUKT Page 22
{
//methods and fields
}
In java programming one derived class can extends only one base class because java
programming does not support multiple inheritance through the concept of classes, but it can be
supported through the concept of Interface.
Whenever we develop any inheritance application first create an object of bottom most derived
class but not for top most base class.
When we create an object of bottom most derived class, first we get the memory space for the
data members of top most base class, and then we get the memory space for data member of other
bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top most base
classes.
If we do not want to give the features of base class to the derived class then the definition of the
base class must be preceded by final hence final base classes are not reusable or not inheritable.
If we are do not want to give some of the features of base class to derived class than such features
of base class must be as private hence private features of base class are not inheritable or
accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but constructors
of base class can not be inherited because every constructor of a class is made for initializing its
own data members but not made for initializing the data members of other classes.
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five types of
inheritance; they are:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
1. Single inheritance
In single inheritance there exists single base class and single derived class.
Syntax
classClassName-2extendsClasssName-1
{
variable declaration;
Method declaration;
}
Explanation
1. ClassName-1 and ClassName-2 represents name of the base and derived classes respectively.
2. extends is one of the keyword used for inheriting the features of base class into derived class it
improves the functionality of derived class.
Example of Single Inheritance
class Faculty
float salary=30000;
float bonous=2000;
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
Output
Salary is: 30000.0
Bonous is: 2000.0
2. Hierarchical inheritance
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 =new B();
C obj2 =new C();
D obj3 =new D();
Single base class + single derived class + multiple intermediate base classes.
An intermediate base class is one in one context with access derived class and in another context same
class access base class.
Hence all the above three inheritance types are supported by both classes and interfaces.
Output
Total Salary is: 37000.0
4. Hybrid inheritance
Combination of any inheritance type In the combination if one of the combination is multiple inheritance
then the inherited combination is not supported by java through the classes concept but it can be
supported through the concept of interface.
}}
5. Multiple inheritance
In multiple inheritance there exist multiple classes and single derived class.
Due to ambiguity problem java does not support multiple inheritance at class level.
Example
class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
void disp()
System.out.println("How are you ?");
}
}
class C extends A,B //suppose if it were
{
public static void main(String args[])
{
C obj=new C();
obj.disp();//Now which disp() method would be invoked?
}
}
In above code we call both class A and class B disp() method then it confusion which class method is
call. So due to this ambiguity problem in java do not use multiple inheritance at class level, but it support
at interface level.
}
class B extends A
{
public void fun1()
{
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}
Output
It gives an error
Example
final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.show();
}
}
Output
It gives an error
Super keyword:
Super is a reference variable that is used to refer immediate parent class object. Uses of super keyword:
1. super is used to refer immediate parent class variable.
2. super() is used to invoke immediate parent class constructors
3. super is used to invoke immediate parent class method
Super keyword is always pointing to base class (scope outside the class) features and "this" keyword is
always pointing to current class (scope is within the class) features.
1. Use of super with variables: This scenario occurs when a derived class and base class has same data
members. In that case there is a possibility of ambiguity for the JVM. We can understand it more clearly
using this code snippet:
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
Output
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could access
maxSpeed of base class in sublcass using super keyword.
2. Use of super with methods:This is used when we want to call parent class method. So whenever a
parent and child class have same named methods then to resolve ambiguity we use super keyword. This
code snippet helps to understand the said usage of super keyword.
Example
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
Output
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be invoked.
3. Use of super with constructors: super keyword can also be used to access the parent class
constructor. One more important thing is that, ‘’super’ can call both parametric as well as non parametric
constructors depending upon the situation. Following is the code snippet to explain the above concept:
In the above example we have called the superclass constructor using keyword ‘super’ via subclass
constructor.
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways. There are
two types of polymorphism in Java:
1. Method Overloading in Java ( static polymorphism)
2. Method Overriding in Java (dynamic polymorphism)
Syntax
class class_Name
{
Returntype method()
{.........}
Returntype method(datatype1 variable1)
{.........}
Returntype method(datatype1 variable1, datatype2 variable2)
{.........}
Returntype method(datatype2 variable2)
{.........}
Returntype method(datatype2 variable2, datatype1 variable1)
{.........}
}
Whenever same method name is existing in both base class and derived class with same types of
parameters or same order of parameters is known as method Overriding. Here we will discuss about
Overriding in Java. Without Inheritance method overriding is not possible.
class OverridingDemo
{
public static void main(String args[])
{
}
}
Output
Man walking slowly