Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Java OOPs

The document discusses key concepts of object-oriented programming (OOP) in Java, including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It provides examples of how these concepts are implemented in Java, such as defining classes with fields and methods, creating objects, and initializing objects using constructors. The document also compares the advantages of OOP over procedure-oriented programming.

Uploaded by

ujjawalr9027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Java OOPs

The document discusses key concepts of object-oriented programming (OOP) in Java, including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It provides examples of how these concepts are implemented in Java, such as defining classes with fields and methods, creating objects, and initializing objects using constructors. The document also compares the advantages of OOP over procedure-oriented programming.

Uploaded by

ujjawalr9027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Learning JAVA

OOPS
• 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 car is an object because it has states like
color, name etc. as well as behaviors like speed 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.
• 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.
• In Java, we use abstract class and interface to
achieve abstraction.
• 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.
Advantage of OOPs over Procedure-oriented
programming language

• 1) OOPs makes development and


maintenance easier, whereas, in a procedure-
oriented programming language, it is not easy
to manage if code grows as project size
increases.
• 2) OOPs provides data hiding, whereas, in a
procedure-oriented programming language,
global data can be accessed from anywhere.
• 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.

What is an object in Java

• An entity that has state and behavior is known as an


object e.g., chair, bike, marker, pen, table, car, etc. It
can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.
• An object has three characteristics:
• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
• Identity: An object identity is typically implemented via
a unique ID. The value of the ID is not visible to the
external user. However, it is used internally by the JVM
to identify each object uniquely.
What is a class in Java

• A class is a group of objects which have common


properties. It is a template or blueprint from
which objects are created. It is a logical entity. It
can't be physical.
• A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
• Instance variable in Java
– A variable which is created inside the class but outside the method is
known as an instance variable. Instance variable doesn't get memory
at compile time. It gets memory at runtime when an object or instance
is created. That is why it is known as an instance variable.

• Method in Java
– In Java, a method is like a function which is used to expose the
behavior of an object.
– Advantage of Method
• Code Reusability
• Code Optimization

• new keyword in Java


– The new keyword is used to allocate memory at runtime. All objects
get memory in Heap memory area.

• //Java Program to illustrate how to define a class and fields
• //Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference varia
ble
System.out.println(s1.name);
}
}
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Test it NowOutput:
0 null
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Test it NowOutput:
101 Sonoo
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the
insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Test it NowOutput:
111 Karan 222 Aryan
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Anonymous object
• Anonymous simply means nameless. An
object which has no reference is known as an
anonymous object. It can be used at the time
of object creation only.
• If you have to use an object only once, an
anonymous object is a good approach. For
example:
• new Calculation();//anonymous object
Example of anonymous object.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial is 120
• //Java Program to demonstrate the working of a banking-system
• //where we deposit and withdraw amount from our account.
• //Creating an Account class which has deposit() and withdraw() methods
class Account{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Constructors in Java
• In Java, a constructor is a block of codes
similar to the method. It is called when an
instance of the class is created. At the time of
calling constructor, memory for the object is
allocated in the memory.
• It is a special type of method which is used to
initialize the object.
• Every time an object is created using the
new() keyword, at least one constructor is
called.
• It calls a default constructor if there is no constructor
available in the class. In such case, Java compiler provides a
default constructor by default.
• There are two types of constructors in Java: no-arg
constructor, and parameterized constructor.
• Note: It is called constructor because it constructs the
values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and
synchronized
• There are two types of
constructors in Java:

–Default constructor (no-arg


constructor)
–Parameterized constructor

Java Default Constructor
• A constructor is called "Default Constructor"
when it doesn't have any parameter.
• Syntax of default constructor:
• <class_name>(){}
• Example of default constructor
• In this example, we are creating the no-arg
constructor in the Bike class. It will be invoked at
the time of object creation.
• //Java Program to create and call a default constr
uctor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Test it NowOutput:
Bike is created
Rule: If there is no constructor in a class, compiler
automatically creates a default constructor.
//Java Program to demonstrate the use of the parameterized construct
or.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Test it NowOutput:
111 Karan 222 Aryan
Constructor Overloading in Java
• In Java, a constructor is just like a method but
without return type. It can also be overloaded
like Java methods.
• Constructor overloading in Java is a technique
of having more than one constructor with
different parameter lists. They are arranged in
a way that each constructor performs a
different task. They are differentiated by the
compiler by the number of parameters in the
list and their types.
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
Java Copy Constructor

• There is no copy constructor in Java. However, we


can copy the values from one object to another
like copy constructor in C++.
• There are many ways to copy the values of one
object into another in Java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
• In this example, we are going to copy the values
of one object into another using Java constructor.
//Java program to initialize the values from one object to another obje
ct.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Test it NowOutput:
111 Karan 111 Karan
• Copying values without constructor
• We can copy the values of one object into another by
assigning the objects values to another object. In this
case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Test it NowOutput:
111 Karan 111 Karan

You might also like