SlideShare a Scribd company logo
Introduction to Java Programming Language
UNIT 7
[Introduction to OOPS : Problems in procedure oriented approach, Features of Object Oriented Programming
System, Object creation, Initializing the instance variable, Constructors.]
Procedure Oriented Programming (POP) decomposes the problems into small parts and then solve
each part using one or more functions.
Problems in procedure oriented approach
• Importance is not given to data but to functions as well as sequence of actions to be done i.e.
algorithm.
• Data moves openly around the system from function to function. It includes Global data,
created for sharing some required information across the system. This free or open access
can result in corruption of data accidentally.
• Adding new data or functionality to change the work flow require going back and modifying
all other parts of the program. In a large program it is very difficult to find or identify what
data is being used by which function.
• procedural code have a tendency to be difficult to understand, as it evolves, it becomes even
harder to understand, and thus, harder to modify.
• It is often difficult to design because it does not model the real world problem very well.
• It is difficult to create new data types. The ability to create the new data type of its own is
called extensibility. Procedure oriented programming is not extensible.
Features of Object Oriented Programming System
To overcome the limitation of Procedural oriented programming languages Object oriented
programmin languages were developed. Following are the features of OOPS:
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
1. Emphasis on data rather than procedure.
2. Programs are divided into small parts called object.
3. Data structures are designed such that they characterized the objects [Class].
4. Data and related functions are enclosed in classes itself [Encapsulation].
5. Data is secured as they can’t be accessed by external functions [Data Hiding].
6. Objects may communicate with each other through functions [Message Passing].
7. Follows bottom-up approach in program design.
8. Using inheritance, a class can acquire properties of another pre-defined class [Inheritance].
9. Data Type can be created based on the necessity.
10. An operation may exhibite different behaviours in different instances. The behaviour
depends upon the types of data used in the operation [Polymorphism].
Object Creation
When we create class then we are creating new data type. Newly created data type is used to
create an Object of that Class Type. For example following is an example 'Rectangle.java', which
defines a new data type (class) 'Rectangle' and object of this class 'myrect1' is created.
class Rectangle{
int length;
int breadth;
public static void main(String a[]){
Rectangle myrect1; // Declaration
myrect1 = new Rectangle(); // Allocation and assigning
myrect1.length = 32;
myrect1.breadth = 15;
System.out.println("   Rectangle   length   is
"+myrect1.length+" and n Rectangle breadth is "+myrect1.breadth);
}
}
Creating object is two step process:
 Step 1 : Declaration of Variable of Type Class
Rectangle myrect1;
▪ Above Declaration will just declare a variable of class type.
▪ Declared Variable is able to store the reference to an object of Rectangle Type.
▪ As we have not created any object of class Rectangle and we haven’t assigned
any reference to myrect1, it will be initialized with null.
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
 Step 2 : Allocation and Assigning Object to variable of class Type
myrect1 = new Rectangle();
▪ Above Statement will create physical copy of an object.
▪ This Physical Copy is then assigned to an variable of Type Class i.e myrect1.
▪ Note : myrect1 holds an instance of an object not actual object. Actual Object is
created elsewhere and instance is assigned to myrect1.
To summarize:
• First statement will just create variable myrect1 which will store address of actual object.
• First Statement will not allocate any physical memory for an object thus any attempt
accessing variable at this stage will cause compile time error.
• Second Statement will create actual object ranndomly at any memory address where it
found sufficient memory.
• Actual memory address of Object is stored inside myrect1.
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
Instead of two seperate statements:
Rectangle myrect1 ;
myrect1 = new Rectangle();
single statement given below can also be used:
Rectangle myrect1 = new Rectangle();
Initializing the instance variable
Variables which are defined without 'static' keyword and outside any method in class is called
instance variable. Instance variables are object specific i.e. each object will have their own copy of
instance variables. Instance variables are also called class properties, fields or data member. Each
instance variable lives in memory for the life of the object it is owned by. Instance variables are
different from local variables, which are defined inside a method and has limited scope. Following
are some of the key differences between instance variable and local variable:
Difference Instance Variable Local Variable
Scope Instance variables can be been seen by all
methods in the class.
Local variables are visible only in the
method or block they are declared.
Declaration Instance variables are declared inside a
class but outside a method.
Local variables are declared inside a
method or a block.
Life Time Instance variables are created using new
and destroyed by the garbage collector
when there are no reference to them.
Local variables are created when a
method is called and destroyed when
the method exits.
Acceess
Modifiers
instance variables can have access
modifiers ( private, public, protected etc.)
local variables will not have any
access modifiers.
Access instance variables can be accessed outside
the class, if they are declared as public.
Local variables can't be accessed from
outside the methods or blocks they are
declared in.
Storage Instance variables are stored in heap. Local variables are stored in stack.
Initialization If no value is assigned to Instance
variables, they will have default values
based on their type. Following is the list of
default values for different types:
Instance Variable Type Default Value
boolean false
byte (byte)0
short (short)0
int 0
long 0L
char u0000
float 0.0f
double 0.0d
Object null
Local variables must be assigned some
value by the code, otherwise the
compiler generates an error.
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
Accessing Instance Variable:
• Using dot operator - If the instance variable is declared as public, it can be accessed using
dot operator (ex- myrect1.length is the above given code).
• Using public member method of the class – If the instance variable is not public, then it
will not be visible outside the class, but it can be accessed by any method, which is defined
in the class itself (member method). So, if there is any method, which is declared as public
can be used to access the instance variable.
For example Rectangle.java (code listed in above section) can be re-written as
Rectangle1.java, when the fields 'length' and 'breadth' of the class Rectangle is defined as
private and not public.
class Rectangle1{
private int length;
private int breadth;
void rectDesc(){
length = 32;
breadth = 15;
System.out.println("   Rectangle   length   is   "+length+"
and n Rectangle breadth is "+breadth);
}
public static void main(String a[]){
Rectangle1 myrect1; // Declaration
myrect1 = new Rectangle1(); // Allocation and assigning
myrect1.rectDesc();
}
}
Here, rectDesc() is a public member method, which is able to access the instance variable, even if
they are private. This method can be accessed from outside the class Rectangle1 using its object
myrect1.
Initializing instance variable:
For initializing an instance variable, it needs to be accessible in someways. And now, we know that
any instance variable can be accessed in following ways:
1. Direct initialization: The instance variable can be assigned a value directly, when they are
declared in a class.
Class <className>{
<type> <instanceVariableName> = <value>
}
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
2. Using dot operator: If instance variable is public, it can be assigned a value using dot
operator having generalized syntax as:
<objectName>.<instanceVariable> = <Value>
3. Using a public member method: If the instance variable is declared as private, it can be
assigned a value using any public instance method, which can accept arguments compatible
with instance variables and assign these values to instance variables. For example:
Class <className>{
private <type> <instanceVariableName_1> ;
private <type> <instanceVariableName_2> ;
public <returnType> methodName( <type> <arg1>, <type> <arg2>, )
<instanceVariableName_1> = <arg1>;
<instanceVariableName_2> = <arg2>;
}
These public methods can be called using instance of the class as shown in example
Rectangle1.java.
As every Objects contain there own copy of Instance Variables. It is very difficult to
design a code that initializes each and every instance variable of each and every object of
Class using an instance method. Java allows objects to initialize themselves when they are
created. Automatic initialization is performed through the use of a constructor, which is
explained in next section.
Constructors
Constructor in java is a special type of method that is used to initialize the object. Like methods, a
constructor also contains collection of statements (i.e. instructions) that are executed at time of
Object creation. Java constructor is invoked at the time of object creation. An object is created using
keyword new like below:
MyClass obj = new MyClass();
Every class has a constructor. If we don't explicitly declare a constructor for any java class, the
compiler builds a default constructor for that class. However when we implement any constructor,
then we don’t receive the default constructor by compiler into our code. Follwoing diagram
demonstrates the idea:
Provided By Shipra Swati, PSCET, Bhagwanpur
Constructor of MyClass is called
Introduction to Java Programming Language
Some important points about Constructor :
1. Constructor name is same as that of “Class Name“.
2. Constructor don’t have any return Type (even Void). But a constructor returns current
class instance.
3. Constructor Initializes an Object.
4. Constructor cannot be called like methods but Constructors are called automatically as
soon as object gets created.
5. Constructor can accept parameter and can be overloaded.
Types of Constructors:
There are two types of constructors:
1. Default constructor or,
(no-arg constructor)
2. Parameterized constructor
• Default Constructor: A constructor that have no parameter is known as default constructor.
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.
class Bike1{
           Bike1() {
                 System.out.println("Bike is created"); 
            }
     public static void main(String args[]){
       Bike1 b=new Bike1();
     }
}
Default constructor provides the default values to the object like 0, null etc. depending on
the type, if no explicit value is assigned.
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
• Parameterized Constructor: A constructor that have parameters is known as parameterized
constructor. Parameterized constructor is used to provide different values to the distinct
objects.
public class Employee {
   int empId;  
   String empName;  
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
           
   public static void main(String args[]){  
        Employee obj1 = new Employee(10245,"Chaitanya");  
        Employee obj2 = new Employee(92232,"Negan");  
        obj1.info();  
        obj2.info();  
   }  
}
• Following is a code that uses two constructors, a default constructor and a parameterized
constructor. When we do not pass any parameter while creating the object using new
keyword then default constructor is invoked, however when we pass a parameter then
parameterized constructor that matches with the passed parameters list gets invoked.
class Example2 {
      private int var;
      //default constructor
      public Example2(){
             this.var = 10;
      }
      //parameterized constructor
      public Example2(int num){
             this.var = num;
      }
      public int getValue() {
              return var;
      }
      public static void main(String args[]){
              Example2 obj = new Example2();
              Example2 obj2 = new Example2(100);
              System.out.println("var is: "+obj.getValue());
              System.out.println("var is: "+obj2.getValue());
      }
}
Provided By Shipra Swati, PSCET, Bhagwanpur
Introduction to Java Programming Language
The program give above has more than one constructor that take different number of
arguments. So, we can say that constructor is overloaded here. Constructor overloading is
a technique in Java in which a class can have any number of constructors that differ in
parameter lists. The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type. So, each constructor can be used performs
different set of task.
A constructor can also accept argument of type class i.e. an object and can copy all the
values of existing object into newly created object. This type of constructor may be termed
as Copy Constructor. Following is an example of copy constructor:
class Student6{
    int id;
    String name;
    Student6(int i,String n){
       id = i;
       name = n;  
    }  
      
    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();  
   }  
}
Other than initialization, another type of operation can also be performed in constructor.
Provided By Shipra Swati, PSCET, Bhagwanpur
Ad

More Related Content

What's hot (20)

Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
Kamlesh Singh
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
Ahmad sohail Kakar
 
SQL Interview Questions For Experienced
SQL Interview Questions For ExperiencedSQL Interview Questions For Experienced
SQL Interview Questions For Experienced
zynofustechnology
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
Geophery sanga
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming concept
Pina Parmar
 
Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming
Prognoz Technologies Pvt. Ltd.
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
javaease
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Oops in java
Oops in javaOops in java
Oops in java
baabtra.com - No. 1 supplier of quality freshers
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
malathip12
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Ahmed Shawky El-faky
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
lykado0dles
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
Zeeshan Khan
 

Similar to Java unit 7 (20)

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
AshutoshTrivedi30
 
Presentation2.ppt java basic core ppt .
Presentation2.ppt  java basic core ppt .Presentation2.ppt  java basic core ppt .
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
DaveEstonilo
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
Kuntal Bhowmick
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
YashikaDave
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
Kuntal Bhowmick
 
Untitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptxUntitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptx
janetvidyaanancys
 
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
MaheshRamteke3
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
Saravanakumar viswanathan
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
jayeshsoni49
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 
Oops
OopsOops
Oops
Sankar Balasubramanian
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Presentation2.ppt java basic core ppt .
Presentation2.ppt  java basic core ppt .Presentation2.ppt  java basic core ppt .
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
DaveEstonilo
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
Kuntal Bhowmick
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
Kuntal Bhowmick
 
Untitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptxUntitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptx
janetvidyaanancys
 
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
100 Java questions FOR LOGIC BUILDING SOFTWARE.docx
MaheshRamteke3
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 
Ad

More from Shipra Swati (20)

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
Shipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
Shipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
Shipra Swati
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Java unit 14
Java unit 14Java unit 14
Java unit 14
Shipra Swati
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
Shipra Swati
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
Shipra Swati
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
Shipra Swati
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
Shipra Swati
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
Shipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7
Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
Shipra Swati
 
Disk Management
Disk ManagementDisk Management
Disk Management
Shipra Swati
 
File Systems
File SystemsFile Systems
File Systems
Shipra Swati
 
Memory Management
Memory ManagementMemory Management
Memory Management
Shipra Swati
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
Shipra Swati
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
Shipra Swati
 
Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
Shipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
Shipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
Shipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7
Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
Shipra Swati
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
Shipra Swati
 
Ad

Recently uploaded (20)

ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 

Java unit 7

  • 1. Introduction to Java Programming Language UNIT 7 [Introduction to OOPS : Problems in procedure oriented approach, Features of Object Oriented Programming System, Object creation, Initializing the instance variable, Constructors.] Procedure Oriented Programming (POP) decomposes the problems into small parts and then solve each part using one or more functions. Problems in procedure oriented approach • Importance is not given to data but to functions as well as sequence of actions to be done i.e. algorithm. • Data moves openly around the system from function to function. It includes Global data, created for sharing some required information across the system. This free or open access can result in corruption of data accidentally. • Adding new data or functionality to change the work flow require going back and modifying all other parts of the program. In a large program it is very difficult to find or identify what data is being used by which function. • procedural code have a tendency to be difficult to understand, as it evolves, it becomes even harder to understand, and thus, harder to modify. • It is often difficult to design because it does not model the real world problem very well. • It is difficult to create new data types. The ability to create the new data type of its own is called extensibility. Procedure oriented programming is not extensible. Features of Object Oriented Programming System To overcome the limitation of Procedural oriented programming languages Object oriented programmin languages were developed. Following are the features of OOPS: Provided By Shipra Swati, PSCET, Bhagwanpur
  • 2. Introduction to Java Programming Language 1. Emphasis on data rather than procedure. 2. Programs are divided into small parts called object. 3. Data structures are designed such that they characterized the objects [Class]. 4. Data and related functions are enclosed in classes itself [Encapsulation]. 5. Data is secured as they can’t be accessed by external functions [Data Hiding]. 6. Objects may communicate with each other through functions [Message Passing]. 7. Follows bottom-up approach in program design. 8. Using inheritance, a class can acquire properties of another pre-defined class [Inheritance]. 9. Data Type can be created based on the necessity. 10. An operation may exhibite different behaviours in different instances. The behaviour depends upon the types of data used in the operation [Polymorphism]. Object Creation When we create class then we are creating new data type. Newly created data type is used to create an Object of that Class Type. For example following is an example 'Rectangle.java', which defines a new data type (class) 'Rectangle' and object of this class 'myrect1' is created. class Rectangle{ int length; int breadth; public static void main(String a[]){ Rectangle myrect1; // Declaration myrect1 = new Rectangle(); // Allocation and assigning myrect1.length = 32; myrect1.breadth = 15; System.out.println("   Rectangle   length   is "+myrect1.length+" and n Rectangle breadth is "+myrect1.breadth); } } Creating object is two step process:  Step 1 : Declaration of Variable of Type Class Rectangle myrect1; ▪ Above Declaration will just declare a variable of class type. ▪ Declared Variable is able to store the reference to an object of Rectangle Type. ▪ As we have not created any object of class Rectangle and we haven’t assigned any reference to myrect1, it will be initialized with null. Provided By Shipra Swati, PSCET, Bhagwanpur
  • 3. Introduction to Java Programming Language  Step 2 : Allocation and Assigning Object to variable of class Type myrect1 = new Rectangle(); ▪ Above Statement will create physical copy of an object. ▪ This Physical Copy is then assigned to an variable of Type Class i.e myrect1. ▪ Note : myrect1 holds an instance of an object not actual object. Actual Object is created elsewhere and instance is assigned to myrect1. To summarize: • First statement will just create variable myrect1 which will store address of actual object. • First Statement will not allocate any physical memory for an object thus any attempt accessing variable at this stage will cause compile time error. • Second Statement will create actual object ranndomly at any memory address where it found sufficient memory. • Actual memory address of Object is stored inside myrect1. Provided By Shipra Swati, PSCET, Bhagwanpur
  • 4. Introduction to Java Programming Language Instead of two seperate statements: Rectangle myrect1 ; myrect1 = new Rectangle(); single statement given below can also be used: Rectangle myrect1 = new Rectangle(); Initializing the instance variable Variables which are defined without 'static' keyword and outside any method in class is called instance variable. Instance variables are object specific i.e. each object will have their own copy of instance variables. Instance variables are also called class properties, fields or data member. Each instance variable lives in memory for the life of the object it is owned by. Instance variables are different from local variables, which are defined inside a method and has limited scope. Following are some of the key differences between instance variable and local variable: Difference Instance Variable Local Variable Scope Instance variables can be been seen by all methods in the class. Local variables are visible only in the method or block they are declared. Declaration Instance variables are declared inside a class but outside a method. Local variables are declared inside a method or a block. Life Time Instance variables are created using new and destroyed by the garbage collector when there are no reference to them. Local variables are created when a method is called and destroyed when the method exits. Acceess Modifiers instance variables can have access modifiers ( private, public, protected etc.) local variables will not have any access modifiers. Access instance variables can be accessed outside the class, if they are declared as public. Local variables can't be accessed from outside the methods or blocks they are declared in. Storage Instance variables are stored in heap. Local variables are stored in stack. Initialization If no value is assigned to Instance variables, they will have default values based on their type. Following is the list of default values for different types: Instance Variable Type Default Value boolean false byte (byte)0 short (short)0 int 0 long 0L char u0000 float 0.0f double 0.0d Object null Local variables must be assigned some value by the code, otherwise the compiler generates an error. Provided By Shipra Swati, PSCET, Bhagwanpur
  • 5. Introduction to Java Programming Language Accessing Instance Variable: • Using dot operator - If the instance variable is declared as public, it can be accessed using dot operator (ex- myrect1.length is the above given code). • Using public member method of the class – If the instance variable is not public, then it will not be visible outside the class, but it can be accessed by any method, which is defined in the class itself (member method). So, if there is any method, which is declared as public can be used to access the instance variable. For example Rectangle.java (code listed in above section) can be re-written as Rectangle1.java, when the fields 'length' and 'breadth' of the class Rectangle is defined as private and not public. class Rectangle1{ private int length; private int breadth; void rectDesc(){ length = 32; breadth = 15; System.out.println("   Rectangle   length   is   "+length+" and n Rectangle breadth is "+breadth); } public static void main(String a[]){ Rectangle1 myrect1; // Declaration myrect1 = new Rectangle1(); // Allocation and assigning myrect1.rectDesc(); } } Here, rectDesc() is a public member method, which is able to access the instance variable, even if they are private. This method can be accessed from outside the class Rectangle1 using its object myrect1. Initializing instance variable: For initializing an instance variable, it needs to be accessible in someways. And now, we know that any instance variable can be accessed in following ways: 1. Direct initialization: The instance variable can be assigned a value directly, when they are declared in a class. Class <className>{ <type> <instanceVariableName> = <value> } Provided By Shipra Swati, PSCET, Bhagwanpur
  • 6. Introduction to Java Programming Language 2. Using dot operator: If instance variable is public, it can be assigned a value using dot operator having generalized syntax as: <objectName>.<instanceVariable> = <Value> 3. Using a public member method: If the instance variable is declared as private, it can be assigned a value using any public instance method, which can accept arguments compatible with instance variables and assign these values to instance variables. For example: Class <className>{ private <type> <instanceVariableName_1> ; private <type> <instanceVariableName_2> ; public <returnType> methodName( <type> <arg1>, <type> <arg2>, ) <instanceVariableName_1> = <arg1>; <instanceVariableName_2> = <arg2>; } These public methods can be called using instance of the class as shown in example Rectangle1.java. As every Objects contain there own copy of Instance Variables. It is very difficult to design a code that initializes each and every instance variable of each and every object of Class using an instance method. Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor, which is explained in next section. Constructors Constructor in java is a special type of method that is used to initialize the object. Like methods, a constructor also contains collection of statements (i.e. instructions) that are executed at time of Object creation. Java constructor is invoked at the time of object creation. An object is created using keyword new like below: MyClass obj = new MyClass(); Every class has a constructor. If we don't explicitly declare a constructor for any java class, the compiler builds a default constructor for that class. However when we implement any constructor, then we don’t receive the default constructor by compiler into our code. Follwoing diagram demonstrates the idea: Provided By Shipra Swati, PSCET, Bhagwanpur Constructor of MyClass is called
  • 7. Introduction to Java Programming Language Some important points about Constructor : 1. Constructor name is same as that of “Class Name“. 2. Constructor don’t have any return Type (even Void). But a constructor returns current class instance. 3. Constructor Initializes an Object. 4. Constructor cannot be called like methods but Constructors are called automatically as soon as object gets created. 5. Constructor can accept parameter and can be overloaded. Types of Constructors: There are two types of constructors: 1. Default constructor or, (no-arg constructor) 2. Parameterized constructor • Default Constructor: A constructor that have no parameter is known as default constructor. 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. class Bike1{            Bike1() {                  System.out.println("Bike is created");              }      public static void main(String args[]){        Bike1 b=new Bike1();      } } Default constructor provides the default values to the object like 0, null etc. depending on the type, if no explicit value is assigned. Provided By Shipra Swati, PSCET, Bhagwanpur
  • 8. Introduction to Java Programming Language • Parameterized Constructor: A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects. public class Employee {    int empId;      String empName;      //parameterized constructor with two parameters    Employee(int id, String name){          this.empId = id;          this.empName = name;      }      void info(){         System.out.println("Id: "+empId+" Name: "+empName);    }                  public static void main(String args[]){           Employee obj1 = new Employee(10245,"Chaitanya");           Employee obj2 = new Employee(92232,"Negan");           obj1.info();           obj2.info();      }   } • Following is a code that uses two constructors, a default constructor and a parameterized constructor. When we do not pass any parameter while creating the object using new keyword then default constructor is invoked, however when we pass a parameter then parameterized constructor that matches with the passed parameters list gets invoked. class Example2 {       private int var;       //default constructor       public Example2(){              this.var = 10;       }       //parameterized constructor       public Example2(int num){              this.var = num;       }       public int getValue() {               return var;       }       public static void main(String args[]){               Example2 obj = new Example2();               Example2 obj2 = new Example2(100);               System.out.println("var is: "+obj.getValue());               System.out.println("var is: "+obj2.getValue());       } } Provided By Shipra Swati, PSCET, Bhagwanpur
  • 9. Introduction to Java Programming Language The program give above has more than one constructor that take different number of arguments. So, we can say that constructor is overloaded here. Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. So, each constructor can be used performs different set of task. A constructor can also accept argument of type class i.e. an object and can copy all the values of existing object into newly created object. This type of constructor may be termed as Copy Constructor. Following is an example of copy constructor: class Student6{     int id;     String name;     Student6(int i,String n){        id = i;        name = n;       }              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();      }   } Other than initialization, another type of operation can also be performed in constructor. Provided By Shipra Swati, PSCET, Bhagwanpur
  翻译: