JV 1
JV 1
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:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
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.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
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.
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.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises
when classes are aware of each other. If a class has the details information of another class,
there is strong coupling. In Java, we use private, protected, and public modifiers to display
the visibility level of a class, method, and field. You can use interfaces for the weaker
coupling because there is no concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The java.io package is a highly cohesive package
because it has I/O related classes and interface. However, the java.util package is a weakly
cohesive package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one
to many). Also, many MP's can have one prime minister (many to one), and many ministers
can have many departments (many to many).
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance
represents the is-a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all
the child objects will be deleted automatically.
3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
Variables
Local Variables
Local variables are declared inside a method. Individual methods can have the same variable name as another
method within a program. Local variables are only visible inside its individual method. Local variables are created
when the method is constructed and destroyed when the method is terminated.
publicclassVariableExample{
publicvoid Age() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
publicstaticvoid main(String args[]) {
VariableExamplelv = newVariableExample();
lv.Age();
}
}
Parameter Variables
Parameter variables are declared and passed int o methods. After a parameter variable is declared, it is
implemented like a local variable. Therefore, a local variable and parameter variable cannot have the same name.
Keywords are not required for a parameter variable. However, the data type and variable name must be
surrounded by a parenthesis after the method name.
publicclassVariableExample
{
publicvoidsetMtgAmount(doublemtgAmount)
{
System.out.println("The mortgage payment amount is " + mtgAmount);
}
public static void main(String[] args)
{
VariableExamplepayment = newVariableExample ();
payment.setMtgAmount(99000);
}
}
Instance Variables
Instance variables are declared inside a class, outside of a method, and can be optionally accessed after creating an
object. The values of an instance variable are unique to each object. Instance variable can be declared before or
after it is initialized with visibility to all methods in a class. Default values for a number is zero, for boolean the
default is false, and an object reference default is null.
Every time when you create an object memory will be allocated to the instance variable
for example
public class VariableExample{
int j = 20;
publicstaticvoid main(String[] args) {
InstanceVariable f = new InstanceVariable();
InstanceVariable f1 = new InstanceVariable();
}
}
in the above example we have an int variable with name “j” and created two objects for the class
so j variable will be allocated memory two time one for object f and one for object f1 Access
modifiers can be given for instance variables.
public classVariableExample
{
intyearsExist = 34;
public static void main(String[] args)
{
VariableExampleyears = newVariableExample ();
System.out.println("Org existed for " + years.yearsExist + " years");
}
}
3. Static variables:
Static variable (“static” Keyword = Class Variables)
If a variable is declared as static then the variable is said to be static variable. Example: static int y = 0;
A static variable is shared by all the object. If a variable is non static then for each object the memory is allocated
but for static variable only one time memory allocated and all the object uses that common memory location.
Static will be used in the memory management .JVM first looks for static variables and static methods before
starting programme execution from main method.
When a variable is declared with the keyword “static”, it’s called a “class variable”. As memory is allocated before
creating object static variable is can be accesses using class name rather that object name so static variables are
class variable not associated with object.
public classVariableExample
{
static int numDays = 30;
public static void main(String[] args)
{
intnumDays = 50;
VariableExampledays = newVariableExample ();
System.out.println("Java can be mastered in " + VariableExample.numDays + " days");
System.out.println("Selenium can be mastered in " + days.numDays + " days");
System.out.println("Do you think you can master Java/Selenium " + numDays + "days");
}
}
Output:
Java can be mastered in 30 days
Selenium can be mastered in 30 days
Do you think you can master Java/Selenium in 50 days
public classVariableExample {
static inti = 0;
VariableExample() {
i = i + 1;
System.out.println(i);
}
public static void main(String[] args) {
VariableExamplet = newVariableExample ();
VariableExamplet1 = newVariableExample ();
}
}
Output: 1 ,2
public classVariableExample {
inti = 0;
VariableExample() {
i = i + 1;
System.out.println(i);
}
public static void main(String[] args) {
VariableExamplet = newVariableExample ();
VariableExamplet1 = newVariableExample ();
}
}
Output: 1 ,1
1: Final variables
Final variables are nothing but constants. We cannot change the value of a final variable once it
is initialized.
classFinal Var
{
final int MAX_VALUE=99;
voidmyMethod()
{
MAX_VALUE=101;
}
Output:
Exceptionin thread "main" java.lang.Error: Unresolved compilation problem:
Thefinal field Final Var.MAX_VALUE cannot be assigned
2) Final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.
classFMethod{
finalvoid demo()
{
System.out.println("FMethod Class Method");
}
}
classFSubextendsFMethod
{
voiddemo ()
{
System.out.println("ABC Class Method");
}
public static void main(String args[]){
FSubobj= newFSub();
obj.demo();
}
}
Output: Compilation error, Cannot override the final method from FMethod
3) Final class
If we declare a class as final we cannot extend a final class.
final classFClass {
}
classFsubextendsFClass {
void demo() {
System.out.println("My Method");
}
Output: The type Fsub cannot subclass the final class FClass
class Account{
inta;
intb;
In the method Set data, the arguments (local variables) are declared as a and b, while the instance variables are
also named as a and b(Below left image)
During execution, the compiler is confused. Whether "a" on the left side of the assigned operator is the instance
variable or the local variable. Hence, it does not set the value of 'a' or ‘b’ when the method set data is called.
The solution is the "THIS" keyword.Append both 'a' and 'b' with the "this" keyword followed by a dot (.)
operator.During code execution when an object calls the method 'setdata'. The keyword 'this' is replaced by the
object handler "obj." (above right image)
class Account{
inta;
intb;
Output:Valueof A =2 Value of B =3
If local variables (formal arguments) and instance variables are same, there is need to use this keyword
If local variables (formal arguments) and instance variables are different, there is no need to use this keyword
Suppose you are smart enough to choose different names for your instance variable and methods arguments. But
this time around, you create two objects of the class, each calling the set data method.
How the compiler will determine whether it is supposed to work on instance variable of object 1 or object 2?
class Account{
inta;
intb;
Value of A =2 , B =3 , A =4 , B =5
The compiler implicitly appends the instance variable with "THIS" keyword.Such that when object 1 is calling the
set data method, an instance variable is appended by its reference variable.While object 2 is calling the set data
method, an instance variable of object 2 is modified.This process is taken care by the compiler itself .
Constructors in Java
Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of
statements(i.e. instructions) that are executed at time of Object creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height).
But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with
no value defined for its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly
done by the programmer or by Java itself (default constructor).
Types of constructor
There are two type of constructor in Java:
1. No-argument constructor: A constructor that has no parameter is known as default constructor. If we don’t
define a constructor in a class, then compiler creates default constructor(with no arguments) for the class.
And if we write a constructor with arguments or no-arguments then the compiler does not create a default
constructor.
Default constructor provides the default values to the object like 0, null, etc. depending on the type.
class Geek
{
intnum;
String name;
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = newGeek();
class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = newGeek("adam", 1);
System.out.println("GeekName:" +geek1.name + " &GeekId :" + geek1.id);
}
}
Output:GeekName:adam&GeekId :1
Does constructor return any value?
There are no “return value” statements in constructor, but constructor returns current class instance. We can
write ‘return’ inside a constructor.
Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates
constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
class Geek
{
// constructor with one argument
Geek(String name)
{
System.out.println("one " + "argument - String : " + name);
}
System.out.println("two args:" + "String and Int eger:" + name + " "+ age);
class GFG
{
Publicstaticvoidmain(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments
Output:
one argument - String : Shikhar
twoargs:String and Int eger:Dharmesh 26
1 arg : Long : 325614567
Constructor is a block of code that allows you to create an object of class and has same name as class with no
explicit return type.
Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the
form of variables and methods from its super class but it does not inherit constructor of super class because of
following reasons:
Constructors are special and have same name as class name. So if constructors were inherited in child class then
child class would contain a parent class constructor which is against the constraint that constructor should have
same name as class name. For example see the below code:
class Parent {
public Parent()
{
}
Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by
using a super class’s constructor we can access/initialize private members of a class.
A constructor cannot be called as a method. It is called when object of the class is created so it does not make
sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class
constructor if there is no explicit call to super or this
Inheritance
A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a
subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the
Superclass and adds its own, unique elements. To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
// Create a superclass.
class A {
inti, j;
voidshowij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
intk;
voidshowk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
classSimpleInheritance {
publicstaticvoid main(String args[]) {
A superOb = newA();
B subOb = newB();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output :
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
A class member that has been declared as private will remain private to its class. It is not accessible by any code
outside its class, including subclasses.
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
voidprintColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
publicstaticvoid main(String args[]){
Dog d=newDog();
d.printColor();
}}
super.Method
Polymorphism
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
In Java it is possible to define two or more methods within the same class that share the same name, as long as their
parameter declarations are different.
In java, Method Overloading is not possible by changing the return type of the method only.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
class Adder{
staticint add(inta,intb){returna+b;}
staticint add(inta,intb,intc){returna+b+c;}
}
class TestOverloading1{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer
arguments and second add method receives two double arguments.
class Adder{
staticint add(inta, intb){returna+b;}
staticdouble add(doublea, doubleb){returna+b;}
}
class TestOverloading2{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:
class Adder{
staticintadd(inta,intb){returna+b;}
staticdoubleadd(inta,intb){returna+b;}
}
class TestOverloading3{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
In other words, If a subclass provides the specific implementation of the method that has been declared by one of
its parent class, it is known as method overriding.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.Method invocation is determined by the JVM not compiler, it is
known as runtime polymorphism
A real example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate
of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest
class Bank{
intgetRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
intgetRateOfInterest(){return 8;}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Java Abstraction
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
2. Interface (100%)
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class
The type subclass must implement the inherited abstract method of base class
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
The abstract class can also be used to provide some implementation of the interface. In such case, the
end user may not be forced to override all the methods of the interface.
interface A{
void a();
void b();
void c();
void d();
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output: I am a
I am b
I am c
I am d