Chapter - 4 Notes2
Chapter - 4 Notes2
1) Procedure Oriented
2) Object Oriented
-> If we want to add more functionalities then we need to develop more functions
-> If we want to develop a project using OOP lanaguage then we have to use Classes
& Objects
-> Any language which follows OOPS Principles is called as OOP Language
===============
OOPS Principles
===============
1) Encapsulation
2) Abstraction
3) Polymorphism
4) Inhertience
================
Encapsulation
===============
-> Encapsulation is used to combine our variables & methods as single entity / unit
//variables
// methods
}
============
Abstraction
=============
-> Abstraction means hiding un-necessary data and providing only required data
===============
Polymorphism
===============
Ex:-2:
============
Inheritence
============
-> Extending the properties from one class to another class is called as
Inheritence
Note: In java, one child can't inherit properties from two parents at a time
======
Class
======
-> Once class is created then we can create any no.of objects for a class
class <ClassName> {
// variables
// methods
========
Object
========
-> Without having the class, we can' create object (class is mandatory to create
objects)
-> If object is not using then garbage Collector will remove that object from heap
-> Garbage Collector is responsible for memory cleanup activities in JVM heap area.
=================
What is Hash Code
=================
-> We can get hashcode of the object by calling java.lang.Object class hashCode ()
method.
u1.hashCode ( );
Note: java.lang.Object class is by default parent class for all java classes.
============
Variables
============
int a = 10 ;
b) static variables
c) local variables
=================
instance variables
=================
-> Variables which are declared inside the class and outside the method are called
as instance variables
-> instance variables can be accessed by all the methods available in the class
thats why the are called as Global Variables.
-> When we create the object, then only memory will be allocated for instance
variables
Note: If we create 2 objects, then 2 times memory will be allocated for instace
variables
-> Every Object will maintain its own copy of the instance variable
int age;
=============
Static Variables
=============
-> The variables which are declared inside the class and outside the method with
'static' keyword are called as static variables
-> When class is loaded into JVM then immediatley memory will be allocated for
static variables
-> Memory will be allocated for static variables only once when the class is loaded
into JVM
-> All objects of the class will maintain same copy of the static variables
String name;
String email;
long phno;
static String institute;
Student.institute = "ashokit";
=========================================
When to declare variable as static or non-static ?
=========================================
-> If we want to store different value based on object then use instance variable
-> If we want to store same value for all objects then use static variable
==============
Local Variables
==============
-> The variables which are declared inside the method or constructor or block are
called as Local Variables
-> If we declare a variable with in the method, then that variable can be used /
accessed only with in that method
-> If we create a variable with in the method, memory will be allocated for that
variable when that method is executing. After that method execution completed,
local variable will be deleted from memory
class Demo {
System.out.println(a);
System.out.prinltn(b);
}
}
========
Methods
========
-> In a class we can write any no.of methods including main method
-> If we want to execute our method then we have to invoke / call our methods from
main ( ) method.
//logic
return value;
1) Method Declaration
2) Method Body
------------------------------------------
What is Method Declaration ?
------------------------------------------
Method declaration means we are going to decide what is the name of the method ,
what are the parameters it will take and what kind of value is return by the
method.
syntax:
returntype methodname (list of parameters);
--------------------------------
What is returntype ?
-----------------------------
-> returntype is data type that indicates what type of value is return by the
particular method.
-> returntype can be any primitive type or array type or reference type
-> if method does not return any value then return type must be specified using a
java keyword called " void ".
-> specifying returntype is mandatory
-----------------------------------
What is method name ?
----------------------------------
-> To identify and access the method there is a suitable name is given for a method
which is called as method name.
-> a methodname can be any valid java identifier.
-> specifying method name is mandatory
--------------------------------------------
What are method parameters ?
------------------------------------------
-> parameters are the variables that will receive the values that are passed into
the. particular method on which data method will perform the operations.
-> we can write 0 or more number of parameters of any primitive type or array type
or reference type
-------------------------------------------------------------------------------
Method body / Method Definition / Method implementation
-------------------------------------------------------------------------------
-> Method body means we are going to write the group of statements that are
executed by the method.
-> A method body can be written in between a pair of curly braces
syntax:
-> here we can write 0 or more number of statements in between the pair of curly
braces.
-> when we write 0 statements then it is called as null implementation
-> if the return type is specified as other than void then we must return a value
from our method using java keyword called " return ".
syntax:
return value;
- the datatype of the value we return must be match with the datatype that we
specify as return type.
- but if return type specified as void then we must not write any return value
statement.
-> In java we can create any number of methods which are in any of the following 4
combinations of methods
void hello ( ) {
System.out.println("Hello My Friend");
}
int c = a + b ;
return c;
}
S.o.p(name);
// take person age as input, if person age >=18 then return true else return false
if ( age >= 18 ) {
return true;
} else {
return false;
}
=====================
Types of Methods
=====================
-> When we write methods in java class, by default jvm will not execute them
Note: JVM will start our program execution from main method. Main method is called
as entry point for JVM execution
// this is valid
void m1 ( ) {
// this is valid
void m1 (int a, float f){
// this is valid
int add (int a, int b){
int c = a + b;
return c;
}
// this is valid
int add (int a, int b){
return a + b;
}
// this is valid
int div (int a, int b){
return a / b ;
}
// below method is invalid (method return type is int but it is trying to return
string value)
int m1 (String name){
Stirng s1 = name.toUpperCase( ) ;
return s1;
// this is valid
boolean m2 ( int a, int b){
if (a > b )
return true;
else
return false;
// this is valid
boolean m2 (int a, int b){
return a > b ;
// this is valid
boolean m3( ) {
return true ;
}
// this is valid
void c1 (int [ ] arr ){
System.out.println(arr);
}
-----------------------------------------------
public class Student {
Student.greet();
}
void hello() {
System.out.println("Hello My Friend...");
}
//object creation
Methods m = new Methods();
int[] ar = { 1, 2, 3 };
m.print(ar);
m.fullname("ashok", "it");
}
retunr length;
}
//logic
}
return name.toUpperCase( );
----------------------------------------------------------
int ar[ ] = {1,2,3};
String s= Arrays.toString ( ar ) ;
String s1 = sb.reverse ( );
// int length ( )
int x = name.length ( ) ;
--------------------------------------------------------------------
public class Driver {
// instance method
int add(int a, int b) {
int c = a + b;
return c;
}
}
================================
Working with Methods using Objects
================================
-> For every Obect jvm will assign one unique hashcode
-> In Realtime Projects, mainely our methods will deal with Objects only
d.print(s);
}
void print(Student s) {
System.out.println(s.id + " " + s.name);
}
class Student {
int id;
String name;
}
class Employee {
int id;
double salary;
}
public class Driver {
d.print(e);
}
void print(Employee e) {
System.out.println(e.id + "--" + e.salary);
}
class Product {
int pid;
String pname;
double price;
}
class Driver {
void print(Product p) {
System.out.println(p.pid + " " + p.pname + " " + p.price);
}
d.print(p);
}
}
class Docter {
String name;
int age;
}
class Driver {
void print(Docter d) {
System.out.println(d.name + " " + d.age);
}
class Player {
int id;
String name;
int age;
}
class Driver {
psvm(String... args){
Driver d = new Driver( );
d.print (p2);
}
-----------------------------------------------------------------------------------
-------------------------------
// write a java method which will give Person object with data
package ashokit;
class Driver {
}
Person m1() {
Person p = new Person();
p.id = 101;
p.name = "Rani";
p.age = 32;
return p;
}
class Person {
int id;
String name;
int age;
}
-----------------------------------------------------------------------------------
-------------------------------
package ashokit;
class Driver {
College m1() {
return c;
}
class College {
int id;
String name;
}
-----------------------------------------------------------------------------------
-------------------------------
package ashokit;
class Driver {
class Person {
int id;
String name;
int age;
}
-----------------------------------------------------------------------------------
-------------------------------
// write a java method which will return cricket player data based on player number
7 ----> Dhoni
18 ---> Kohli
package ashokit;
class Driver {
if (id == 7) { //false
p.id = 7;
p.name = "dhoni";
p.age = 40;
} else if (id == 18) { // false
p.id = 18;
p.name = "kohli";
p.age = 34;
} else if (id == 45) { // true
p.id = 45;
p.name = "Rohit";
p.age = 38;
}
return p;
}
class Player {
int id;
String name;
int age;
}
-----------------------------------------------------------------------------
int id;
String name;
String m2() {
String s = "hello";
return s;
}
Approach-1:
Approach-2 :
Person[ ] m2(){
// logic
}
--------------------------------------------------------------------------
package ashokit;
int id;
String name;
Person[] m2() {
return arr;
p.m1(p1, p2);
}
}
-----------------------------------------------------------------------------------
--------------
Object : Physical Entity. It is used to access variables & methods of the class
==============
Constructors
==============
-> Constructor shoudn't have any return type (not even void)
Note: If we write return type for the constructor then it will become method
Syntax :
class Demo {
Demo ( ) {
// logic
}
Note: At the time of object creation our class Constructor will be executed.
Constructor is mandatory to create the object.
Note: If we don't write the constructor in class, then java compiler will add one
default constructor to our class.
-> We can check default constructor for the class using below command
Note: If we write constructor in the class, then compiler will not add any
constructor.
class Student {
Student ( ) {
...
}
}
2) Parameterized Constructor
class Student {
class Employee {
==========
this keyword
===========
class Employee {
String name;
float salary;
------------------------------------------------------------------
int id;
String name;
int age;
String gender;
======================
Constructor Overloading
======================
-> Writing more than one constructor with different parameters is called as
Constructor Overloading
class Employee {
Employee(int id){
Employee(double d){
==========================
Access Specifiers / Modifiers
==========================
-> These are used to specify accessibility for our classes, constructors, variables
& methods
1) public
2) private
3) protected
4) default
public : It is used to specify global access for classes, variables, methods and
Constructors
Note: public means anybody can access from inside and outside the class also.
private: It is used to specify local access (with in the class). private variables,
private methods, private constructors can't be accessed outside of the class.
Note: To make our java class as Singleton, we will use private constructor. The
java class which is having only one object is called as Singleton class.
protected : Protected members can be accessed in same package & its sub classes
default : default members can be accessed in same package. When we don't specify
any modifier then it comes under default modifier.
Note: only public and default modifiers are allowed for classes. private and
protected are not allowed.
Note: If we use 'public' for the class name then class name & file name should be
same. We should have only one public class in the java file.
=======
OOPS
=======
Encapsulation : Combining variables & methods as single unit. It is used for data
hiding.
Inheritence : The process of extending properties from one class to another class
is called as inheritence.
=============
Encapsulation
=============
-> We will combine variables & methods as one single unit using Class
==========
Inheritence
==========
-> The process of extending the properties from one class to another class is
called as Inheritence
-> From which class we are extending the properties that class is called as
'Parent' or 'Super' or 'Base' class
-> The class which is extending the properties is called as 'Child class' or 'Sub
class' or 'Derived' class
class User {
// properties
// methods
}
}
Note: In above example 'User' class is acting as Parent class and Student class is
acting as Child class.
int rank;
int rank;
int id;
String name;
void m1() {
System.out.println(" Parent class :: m1 ( ) method called");
}
}
-> Whenever we create child class object, then first it will execute parent class
zero-param constructor and then it will execute child class constructor.
-> Child should be able to access parent propertiece hence parent constructor will
execute first to initialize parent class properties.
int id;
String name;
public User() {
System.out.println("Parent class :: 0-param constructor called ");
}
double salary;
public Employee() {
System.out.println("Child Class :: 0-Param Constructor called");
}
void m2() {
System.out.println("Child class - m2() method called");
}
==================
Types of Inheritence
==================
1) Single Level
2) Multi Level
3) Multiple --------> Not supported by Java due to Ambiguity problem
4) hierarchical
Multiple Inheritence : If one child having more than one parent (Java doesn't
support to avoid ambiguity)
Note: For every java class, java.lang.Object class will act as Parent either
directley or in-directley
-> If our class doesn't have any parent then java.lang.Object will become parent
directley
-> If our class having parent then java.lang.Object will become parent in-directley
Note: Every java class can access methods available in java.lang.Object class.
class Parent {
void m1() {
System.out.println("Parent - Class - m1() Called");
}
void m2() {
System.out.println("Parent - Class - m2() called");
}
}
void m1() {
System.out.println("Child - Class - m1() Called");
}
void m2() {
System.out.println("Child - Class - m2() called");
super.m2();
}
}
=======================================
Methods Execution Flow w.r.r to Inheritence
=======================================
=> When we call a method using Object, first it will check in current class for
that method, if available it will call that method directley. If method not
available in current class then it will check in parent class (It can be direct or
indirect parent). If parent having that method then it will call parent class
method. If parent class also doesn't have method then it will throw Exception.
Note: In inheritence always priority will be given for Child class / Sub class
object. If child class doesn't contain that method then priority will be given to
Parent class method.
===============
Polymorphism
===============
Poly ----> Many
-> If any object is exhibiting multiple behaviours based on the Situation then it
is called as Polymorphism.
Ex: Overloading
Ex: Overriding
==================
Method Overloading
===================
-> The process of writing more than one method with same name and different
parameters is called as Method Overloading.
c.add(10, 20);
c.add(10, 20, 30);
=> When methods are performing same operation then we should give same name hence
it will improve code readability.
Ex:
=> In Method Overloading scenario, compiler will decide method should be called.
For example if we write like below then program will fail it compilation stage.
================
Method Overriding
=================
-> The process of writing same methods in Parent class & Child class is called as
Method Overriding.
class Parent {
void m1( ) {
// logic
}
}
void m1 ( ){
//logic
}
Note: When we don't want to execute Parent method implementation, then we can write
our own implementation in child class using method Overriding.
class RBIBank {
boolean checkElgibility() {
// docs verification logic
return true;
}
double getHomeLoanRofi() {
return 10.85;
}
}
}
}
NOte: Object class equals ( ) method will compare address of the objects where
String class equals ( ) method will compare content of the objects.
==============================
Types of Relations in Java Classes
==============================
===================
IS-A relation Example
===================
-> If one class wants to re-use all the properties of another class then we will go
for IS-A relation.
class User {
int id;
String name;
void speak ( ){
System.out.println("Hi, My Id is : "+ id + ", My Name : "+ name);
}
}
-> If one class wants to re-use some properties of another class then we will go
for HAS-A relation.
class Engine {
int id;
String name;
String fuelType;
void start ( ){
System.out.println("Engine Starting....");
}
}
class Car {
void drive ( ){
Engine e = new Engine ( ); // HAS-A Relation
e.start ( );
System.out.println("Journey Started");
}
psvm(String[] args){
Car c = new Car ( );
c.drive ( );
}
}
=============
final keyword
=============
1) class level
2) variable level
3) method level
-> final classes can't be inherited. We can't extend properties from final classes.
Final classes are immutable.
-> final variables are nothing but constants. Final variable value can't be
modified.
public final int pi = 3.14;
pi = 4.32; // invalid
===========
Abstraction
===========
-> The process of hiding un-necessary data and providing only useful data is called
as Abstraction.
=============
Method Types
=============
1) Concrete Method
2) Abstract Method
public void m1 ( )
{
-> The method which doesn't contain body is called as 'Abstract method'
Note: By using 'abstract' keyword we can create abstract methods & abstract
classes.
==========
Interfaces
===========
-> Once interface is created then anybody can provide implementation for the
interface
Note: One java class can extend properties from only one class and it can
implement Multiple interfaces at a time.
======================
Interface Example
=====================
=> Interface reference variable can hold its implementation class object.
Ex:
=> When method is taking interface a parameter that means that method is expecting
interface implementation class object as parameter.
=> When method is having Interface as a return type that means that method will
return interface implementation object as return type
-> If interface doesn't contain any method then that interface is called as 'Marker
Interface'
-> If our class implements pre-defined marker interface then JVM will treat our
classes as special classes and JVM will provide special functionality based on the
marker interface we have implemented.
Note: We can create our own marker interfaces but there is no use because JVM don't
know abt our marker interfaces.
-> The interface which contains only one abstract method is called as Functional
Interface.
-> Functional Interfaces are introduced to called 'Lambda Expressions'.
-----------------------------------------------------------------------------------
------------------------
-> In Interface we can declare variables also, by default they are public static
final.
===============
Abstract Classes
===============
-> The class which contains both concrete and abstract methods is called as
abstract class.
-> We can write constructor in abstract class but we can't create Object
-> When we extend properties from abstract class then it is mandatory to override
all abstract methods of that class
-> Abstract class constructor will be executed when we create object for child
class.
public Machine() {
System.out.println("Machine Constructor");
}
@Override
public void fillFuel() {
System.out.println("filling fuel tank....");
}
=> abstract means override in child where as 'final' means don't override .
=> When we implement any interface then we have to implement all the abstract
methods of that interface
=> When we extend abstract class, we need override all abstract methods
=> Abstract class constructor will be executed when we create object for sub class.
=> If interface contains only one method then it is called Functional Interface
=> If interface doesn't have any method then it is called as Marker interface
=> When we don't know implementation for methods then we will go for Interfaces
=> When we know partial implementation for methods then we will go for abstract
classes
============
Blocks in java
============
-> Block means some part or some piece of information or some piece of code
1) instance block
2) static block
==============
Instance Block
=============
-> If you want to execute some piece of code when object is created then we can go
for instance block
-> Instance block will be executed before constructor execution
syntax:
{
// stmts
}
==============
static Block
=============
-> If you want to execute some piece of code when class is loaded into JVM then we
can go for static block
-> static block will execute before main ( ) method execution
syntax:
static
{
// stmts
}
Q) What is static control flow & instance control flow in java program ?
==================
Static Control Flow
==================
-> When class is loaded into JVM then static control flow will start
-> When we run java program, JVM will check for below static members & JVM will
allocate memory for them in below order
a) static variables
b) static methods
c) static blocks
-> Once memory allocation completed for static members then it will start execution
in below order
a) static block
b) static method (if we call) -- only main method will
execute automatically by jvm
c) static variable
-> static variables can be accessed directley in static blocks and static methods.
Note: If we want to access any instance method or instance variable in static area
then we should create object and using that object only we can access. We can't
access directley without object.
====================
Instance Control Flow
====================
-> Instance control flow will begin when object is created for a class
a) instance variables
b) instance methods
c) instance blocks
-> Once memory allocation completed then execution will happen in below order
a) instance block
b) constructor
c) instance methods (if we call)
Note: static members can be access directley in instance areas becase for static
memebers memory aready allocated at the time of class loading.
{
System.out.println("i am from instance block");
}
public Demo() {
System.out.println("I am from constructor");
}
static {
System.out.println("I am from static block");
}
public static void main(String[] args) {
System.out.println("i am from main method...");
Demo d = new Demo();
}
}
===================
java.lang.Object class
===================
-> Object class will act as super class for all the classes in java either
directley or in-directley
Note: If our class doesn't have any super class then Object class will become
direct Super class. If our class having any super class then Object class will
become in-direct super class.
-> Object class having 11 methods, those 11 methods are by default available for
every java object.
5) int hashCode( )
6) String toString( )
7) notify ( )
8) notifyAll ( )
9) void wait ( )
===========================
public String toString ( ) method :
===========================
-> When we print any object or when we call toString ( ) method by default it will
call Object class toString ( ) method
---------------------------------------------------------------------
Object class toString( ) method implementation
---------------------------------------------------------------------
Output : Student@15db9742
-> If we don't like this implementation, then we can override toString ( ) method
in our class like below
int id;
String name;
====================
int hashCode ( ) method
=====================
-> When we create object for a class then JVM will assign one unique hashcode for
every Object
-> If we don't want to execute Object class hashCode ( ) method then we can
override hashCode ( ) method in our class.
int id;
String name;
===============================
boolean equals ( Object obj ) method
===============================
-> equals ( ) method is used to compare one object with another object and returns
boolean value. If objects are same then it will return true otherwise it will
return false value.
Note: Object class equals( ) method will compare address of the object not content.
int id;
String name;
}
}
Note: In String class equals ( ) method overriden to compare content of objects
thats why in above program for Strings we are getting 'true' as ouput. For Student
class it is checking address hence we are getting 'false' as output.
-> If we want to compare content of our Student objects then we need to override
like below
int id;
String name;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) // s1 == s2
return true;
if (obj == null) // s2 == null
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj; // typecasting
if (id != other.id) // s1.id != s2.id
return false;
if (name == null) { // s1.name == null
if (other.name != null)
return false;
} else if (!name.equals(other.name)) // !s1.name.equals(s2.name)
return false;
return true; // ---> true
}
}
=======================
Class getClass ( ) method
========================
}
}
===============
clone ( ) method
===============
-> This method is used to create duplicate object for the given object
-> If we want to clone any object then that class should implement Cloneable
interface which is marker interface.
-> If your class implements Cloneable interface then only JVM will allow you to
clone the object of that class.
}
}
Ans)
=================
finalize ( ) method
=================
-> When garbage collector removing any object from JVM then it will call finalize (
) method
finalize ( )
clone ( )
equals ( )
hashCode ( )
toString ( )
getClass ( )
notify ( )
notifyAll ( )
wait ( ) - 3 overloaded methods
Object ---> This is also predefined class available in java.lang package. Default
parent for all java classes. It contains 11 methods. Every java class can access
Object class methods by default.
==============
OOPS Summary
==============