SlideShare a Scribd company logo
1 of 9
Download to read offline
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

More Related Content

What's hot

What's hot (20)

Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
SQL Interview Questions For Experienced
SQL Interview Questions For ExperiencedSQL Interview Questions For Experienced
SQL Interview Questions For Experienced
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
 
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)
 
Oop java
Oop javaOop java
Oop java
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming concept
 
Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Oops in java
Oops in javaOops in java
Oops in java
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
 

Similar to Java unit 7

Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh 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.pptxDaveEstonilo
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basicsvamshimahi
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptxmrxyz19
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes completeHarish Gyanani
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
 

Similar to Java unit 7 (20)

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
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
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
Oops
OopsOops
Oops
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Java notes
Java notesJava notes
Java notes
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes complete
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 

More from Shipra Swati

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process SchedulingShipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of ProcessShipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-IntroductionShipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information TechnologyShipra Swati
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process SynchronizationShipra Swati
 

More from Shipra Swati (20)

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

Recently uploaded

What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 

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