SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Objectsand Classes
1
OO Programming Concepts
2
Object-oriented programming (OOP) involves
programming using objects. An object represents
an entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle,
a button, and even a loan can all be viewed as
objects. An object has a unique identity, state, and
behaviors. The state of an object consists of a set
of data fields (also known as properties) with their
current values. The behavior of an object is defined
by a set of methods.
Objects
3
An object has both a state and behavior. The state
defines the object, and the behavior defines what
the object does.
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Data Fields:
radius is 10
Circle Object 2
Data Fields:
radius is 25
Circle Object 3
Data Fields:
radius is 125
A class template
Three objects of
the Circle class
Classes
4
Classes are constructs that define objects of the
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
Classes
5
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
Data field
Method
Constructors
Defining a class
A class is a user defined data type that serve to
define its properties .
Once the class is defined we can create
“variables” of that type using declaration that
are similar to the basic type declaration .
In java these variables are termed as instance
of the classes ,which are actual objects.
6
The basic form of class declaration is as below:
class classname [extends superclass]
{
[variables declarations;]
[method declarations;]
}
7
Adding variables
class Rectangle
{
int length ;
int width ;
}
8
Adding method
The general form of method declaration is :
type mehodname (parameter list)
{
method body;
}
Method declarations has four basic parts
 Method name
 Returns type
 Parameter list
 The body of the method
9
class Rectangle
{
int length ;
int width ;
void getdata(int x,int y)
{
length =x;
width = y;
}
}
10
class Rectangle
{
int length ;
int width ;
void getdata(int x,int y)
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
return(area);
}
}
11
Creating objects
Objects in java are created using the new operator .
The new operator creates an objects of the
specified class and returns a reference to that
objects.
Ex.
Rectangle rect1; //declare
rect1 = new rectangle(); //instantiate
The method rectangle is the default constructor of
the class .we can create any no. of objects of
rectangle 12
Accessing class member
Objectname.variable name
Objectname.methodname(parameter-list) ;
rect1.length =15
13
class Rect
{
int length;
int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return(area);
}
}
illustration of class and object
14
class RectangleArea
{
public static void main(String[]args)
{
int area1,area2;
Rect rect1=new Rect();
Rect rect2=new Rect();
rect1.length = 1;
rect1.width = 2;
area1=rect1.length*rect1.width;
rect2.getdata(5,10);
area2=rect2.rectArea();
System.out.println("area1="+area1);
System.out.println("area2="+area2);
}
}
Constructors
We know that all object that are created need initial
values.
One approach for this is the use of Dot operator
through which we access the instance variables
and then assign values to them individually
In second approach we use method like getdata to
initialize each object individually.
Java supports a special type of method called
constructor that enable an object to initialize
itself when it is created.
15
Replacement of getdata by a constructor method
16
class Rectangle
{
int length ;
int width ;
void getdata(int x,int y)
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
return(area)
}
}
class Rectangle
{
int length ;
int width ;
Rectangle (int x , int y) // constructor
method
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
}
}
illustration of constructors
17
class Recta
{
static int length;
static int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
Recta(int x,int y)
{
length=x;
width=y;
}
Recta ()
{
}
int rectArea()
{
int area=length*width;
return(area);
}
}
class RectArea
{
public static void main(String[]args)
{
int area1,area2;
Recta rect1=new Recta();
Recta rect2=new Recta(10,20);
rect1.length = 1;
rect1.width = 2;
area1=rect1.length*rect1.width;
rect2.getdata(5,10);
area2=rect2.rectArea();
System.out.println("area1="+area1);
System.out.println("area2="+area2);
}
}
Difference between constructors and
methods
 The important difference between
constructors and methods is that
constructors create and initialize objects that
don't exist yet, while methods perform
operations on objects that already exist.
 Constructors can't be called directly; they are
called implicitly when the new keyword
creates an object. Methods can be called
directly on an object that has already been
created with new.
18
 The definitions of constructors and methods
look similar in code. They can take
parameters, they can have modifiers
(e.g. public), and they have method bodies in
braces.
 Constructors must be named with the same
name as the class name. They can't return
anything, even void (the object itself is the
implicit return).
 Methods must be declared to return
something, although it can be void.
19
Static members
In general any class contains two sections . One declares variables and
other declares methods .these variables and methods are called
instance variables and instance methods .
This is because every time we the class is instantiated a new copy of
each of them is created .
If we want to define a member that is common to all the objects and
accessed without using a particular object .that is the member belongs
to the class as a whole rather than the object created from the class
such members are called static members .
Static variables and static methods are often referred as class variables
and class methods in order to distinguish them from their
counterparts instance variables and instance methods.
Static variables are used when we want to have a variable common to all
instance of a class.
Ex: static int count;
static int max(int x,int y)
20
Defining and using static members
Class mathoperation
{
static float mul(float x,float y)
{
return x*y;
}
static float divide(float x , float y)
{
return x/y;
}
}
Class mathapplication
{
public static void main(string args[])
{
float a= mathoperation.mul (4.0,5.0);
float b= mathoperation.divide(a,2.0);
System.out.println(“b=“+b);
}
} 21
Method overloading
In java it is possible to create methods that have
the same name ,but different parameter lists
and different definitions . This is called
overloading . Method overloading is used when
object are required to perform similar tasks but
using different input parameters.
this process is known as polymorphism.
22
Class Room
{
Float length;
Float breadth;
Room (float x, float y) //constructor 1
{ length=x;
breadth = y;
}
Room (float x) //constructor 2
{ int area( )
return (length*breadth)
23
Inheritance :extending a class
The mechanism of deriving a new class from an old one is
called inheritance . The old class is know as base class or
super class or parent class and new class is called
subclass or derived class or child class.
The inheritance allows subclass to inherit all the variable
and methods of their parent classes.
Inheritance may take different forms :
single inheritance (only one super class)
multiple inheritance (several super classes)
hierarchical inheritance (only one super class , many subclasses)
multilevel inheritance (derived from a derived class)
24
Defining a subclass
A subclass may be defined as follows:
class subclassname extends supreclassname
{
variable declaration;
methods declaration;
}
25
26
class Room
{
int length;
int breadth;
Room (int x,int y)
{ length=x;
breadth=y;
area();
}
int area( )
{
return (length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y,int z)
{
super(x,y);
height =z;
}
int volume()
{
return(length*breadth*height);
}
}
public class InherTest
{
public static void main(String args[])
{ BedRoom room1 = new BedRoom(14,12,10);
int area1= room1.area();
int volume1=room1.volume();
System.out.println("Area="+area1);
System.out.println("Volume="+volume1);
}
}
Subclass constructor
A subclass constructor is used to the instance variable of
both the subclass and the super class .
The subclass constructor uses the keyword super to
invoke the constructor method of the super class .
The keyword super is subject to the following condition :
 super may only be used within a subclass constructor
method.
 The call to super class constructor must appear as the
first statement within the subclass constructor .
 The parameter in the super call must match the order
and type of the instance variables in the super class.
27
Overriding methods
Method inheritance enables us to define and use method
repeatedly in subclass without having to define the
method again in subclass .
At some occasions we want an object to respond to the
same method but have different behavior when the
method is called.
This is possible by defining a method in the subclass that
has the same name ,same argument and same return
type as a method in the super class .
Then when the method is called the method defined in the
subclass is invoked and executed instead of the one in
the super class .
This is know as overriding. 28
29
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
System.out.println("Super x="+x);
}
}
class Sub extends Super
{
int y ;
Sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("Super x="+x);
System.out.println("Sub y="+y);
}
}
public class OverrideTest
{
public static void main(String args[])
{
Sub s1= new Sub(100,200);
s1.display();
}
}
Output:
Super x=100
Sub y=200
30
The this Keyword
 The this keyword is the name of a reference
that refers to an object itself. One common use
of the this keyword is reference a class’s
hidden data fields.
 Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
The this keyword is the name of a reference that refers to a
calling object itself. One of its common uses is to reference a
class’s hidden data fields. For example, a data-field name is
often used as the parameter name in a set method for the data
field. In this case, the data field is hidden in the set method.
You need to reference the hidden data-field name in the
method in order to set a new value to it. A hidden static variable
can be accessed simply by using the ClassName.StaticVariable
reference. A hidden instance variable can be accessed by
using the keyword this, as shown in next example
31
32
Reference the Hidden Data Fields
public class Foo {
private int i = 5;
private static double k = 0;
void setI(int i) {
this.i = i;
}
static void setK(double k) {
Foo.k = k;
}
}
Suppose that f1 and f2 are two objects of Foo.
Invoking f1.setI(10) is to execute
this.i = 10, where this refers f1
Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
The this keyword gives us a way to refer to the object
that invokes an instance method within the code of the
instance method. The line this.i = i means “assign the
value of parameter i to the data field i of the calling
object.” The keyword this refers to the object that
invokes the instance method set I, as shown in Figure
10.2(b). The line Foo.k = k means that the value in
parameter k is assigned to the static data field k of the
class, which is shared by all the objects of the class.
33
34
Another common use of the this keyword is to enable a constructor
to invoke another constructor of the same class. For example, you
can rewrite the Circle class as follows:
Final variables and methods
All method and variables can be overridden by default
in subclasses . If we wish to prevent the subclasses
from overriding , we can declare them as final using
the keyword final as a modifier .
Example :
final int SIZE =100;
final void showstatus()
{
}
35
Final classes
Sometimes we may like to prevent a class being
further subclasses for security reasons .
A class that cannot be is called a final class . This is
achieved in java using the keywords final as
follows:
final class Aclass (…)
final class Bclass extends Someclass(…)
Declaring a class final prevent any unwanted
extension to the class.
36
Finalizer methods
Java supports a concept called finalization , which is
just opposite to the initialization .
The finalizer method is simply finalize( ) and can be
added to any class . java calls that method
whenever it is about to reclaim the space for that
object . The finalize method should explicitly
define the task to be performed.
37
Abstract classes and methods
 In java we can do something which is just opposite to final that is we
can indicate that a method must always be redefined in a subclass ,
thus making overriding compulsory .
 This is done using the modifier keyword abstract in the method
definition
Example:
abstract class Shape
{
…………….
…………….
abstract void draw();
………………
}
when a class contains one or more abstract method it should be declared
abstract as in above given example. 38
 While using the abstract class we must satisfy the
following condition :
 We can not use abstract classes to instantiate
object directly.
 The abstract methods of an abstract class must be
define in its subclass .
 We cannot declare abstract constructor or abstract
static methods.
39
Visibility control
 Public Access
Any variable or method is visible to the entire
class in which it is defined but if we want to make
it visible to all the classes outside this class we
need to declare that variable or method as public .
Example:
public int number ;
public void sum( )
{
………….
}
40
Friendly access
 Some times we do not use public modifier ,yet they are
still accessible in other classes in the program .
 When no access modifier is specified the member
defaults to a limited version of public accessibility is
known as “friendly ” level of access .
 The difference between the “public” access and the
“friendly” access is that the public modifier makes field
visible in all classes , regardless of their packages while
the friendly access makes fields visible in same package,
but not in other packages.
 (A package is group of classes stored separately .)
 A package in java is similar to a source file in “C”.
41
Protected access
 The visibility level of a “protected ” field lies in
between the public access and friendly
access.
that is the protected modifier makes the field
visible not only to all classes and subclasses
in the same package but also to subclasses in
other packages .
the non-subclasses in other package cannot
access the “protected ” members.
42
Private access
 private field enjoy the highest level degree of
protection .
 They are accessible only within their own class .
They cannot be inherited by subclasses and
therefore not accessible in subclasses .
 A method declares as private behaves like a method
declared as final .
 It prevent the method from being sub classed .
43
Private protected Access
A field can be declared with two keywords private
and protected together like
private protected int x ;
this gives a visibility level in between the
“protected” access and private access .
This modifier makes the field visible in all subclasses
regardless of what package they are in .
But these fields are not accessible by other classes in
the same package .
44

Weitere ähnliche Inhalte

Was ist angesagt?

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
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
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java pptkunal kishore
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Finalize() method
Finalize() methodFinalize() method
Finalize() methodJadavsejal
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 

Was ist angesagt? (20)

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
class and objects
class and objectsclass and objects
class and objects
 
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)
 
Java program structure
Java program structureJava program structure
Java program structure
 
Friend Function
Friend FunctionFriend Function
Friend Function
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
String in java
String in javaString in java
String in java
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 

Andere mochten auch

Using class and object java
Using class and object javaUsing class and object java
Using class and object javamha4
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagramSadhana28
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
classes & objects introduction
classes & objects introductionclasses & objects introduction
classes & objects introductionKumar
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationshipsPooja mittal
 
LAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural ElementsLAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural ElementsDavid Mullich
 
Introduction To Uml
Introduction To UmlIntroduction To Uml
Introduction To Umlguest514814
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling LanguageShahzad
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagramsbarney92
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignMotaz Saad
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Andere mochten auch (18)

Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
C++ classes
C++ classesC++ classes
C++ classes
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
classes & objects introduction
classes & objects introductionclasses & objects introduction
classes & objects introduction
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationships
 
LAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural ElementsLAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural Elements
 
Introduction To Uml
Introduction To UmlIntroduction To Uml
Introduction To Uml
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling Language
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and Design
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Ähnlich wie Object and class

Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods javPadma Kannan
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdfarchgeetsenterprises
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

Ähnlich wie Object and class (20)

Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods jav
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java class
Java classJava class
Java class
 
1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 

Kürzlich hochgeladen

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Kürzlich hochgeladen (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Object and class

  • 2. OO Programming Concepts 2 Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods.
  • 3. Objects 3 An object has both a state and behavior. The state defines the object, and the behavior defines what the object does. Class Name: Circle Data Fields: radius is _______ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25 Circle Object 3 Data Fields: radius is 125 A class template Three objects of the Circle class
  • 4. Classes 4 Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
  • 5. Classes 5 class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } } Data field Method Constructors
  • 6. Defining a class A class is a user defined data type that serve to define its properties . Once the class is defined we can create “variables” of that type using declaration that are similar to the basic type declaration . In java these variables are termed as instance of the classes ,which are actual objects. 6
  • 7. The basic form of class declaration is as below: class classname [extends superclass] { [variables declarations;] [method declarations;] } 7
  • 8. Adding variables class Rectangle { int length ; int width ; } 8
  • 9. Adding method The general form of method declaration is : type mehodname (parameter list) { method body; } Method declarations has four basic parts  Method name  Returns type  Parameter list  The body of the method 9
  • 10. class Rectangle { int length ; int width ; void getdata(int x,int y) { length =x; width = y; } } 10
  • 11. class Rectangle { int length ; int width ; void getdata(int x,int y) { length=x; width = y; } int rectArea() { int area = length*width; return(area); } } 11
  • 12. Creating objects Objects in java are created using the new operator . The new operator creates an objects of the specified class and returns a reference to that objects. Ex. Rectangle rect1; //declare rect1 = new rectangle(); //instantiate The method rectangle is the default constructor of the class .we can create any no. of objects of rectangle 12
  • 13. Accessing class member Objectname.variable name Objectname.methodname(parameter-list) ; rect1.length =15 13
  • 14. class Rect { int length; int width; void getdata(int x,int y) { length=x; width=y; } int rectArea() { int area=length*width; return(area); } } illustration of class and object 14 class RectangleArea { public static void main(String[]args) { int area1,area2; Rect rect1=new Rect(); Rect rect2=new Rect(); rect1.length = 1; rect1.width = 2; area1=rect1.length*rect1.width; rect2.getdata(5,10); area2=rect2.rectArea(); System.out.println("area1="+area1); System.out.println("area2="+area2); } }
  • 15. Constructors We know that all object that are created need initial values. One approach for this is the use of Dot operator through which we access the instance variables and then assign values to them individually In second approach we use method like getdata to initialize each object individually. Java supports a special type of method called constructor that enable an object to initialize itself when it is created. 15
  • 16. Replacement of getdata by a constructor method 16 class Rectangle { int length ; int width ; void getdata(int x,int y) { length=x; width = y; } int rectArea() { int area = length*width; return(area) } } class Rectangle { int length ; int width ; Rectangle (int x , int y) // constructor method { length=x; width = y; } int rectArea() { int area = length*width; } }
  • 17. illustration of constructors 17 class Recta { static int length; static int width; void getdata(int x,int y) { length=x; width=y; } Recta(int x,int y) { length=x; width=y; } Recta () { } int rectArea() { int area=length*width; return(area); } } class RectArea { public static void main(String[]args) { int area1,area2; Recta rect1=new Recta(); Recta rect2=new Recta(10,20); rect1.length = 1; rect1.width = 2; area1=rect1.length*rect1.width; rect2.getdata(5,10); area2=rect2.rectArea(); System.out.println("area1="+area1); System.out.println("area2="+area2); } }
  • 18. Difference between constructors and methods  The important difference between constructors and methods is that constructors create and initialize objects that don't exist yet, while methods perform operations on objects that already exist.  Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new. 18
  • 19.  The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.  Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).  Methods must be declared to return something, although it can be void. 19
  • 20. Static members In general any class contains two sections . One declares variables and other declares methods .these variables and methods are called instance variables and instance methods . This is because every time we the class is instantiated a new copy of each of them is created . If we want to define a member that is common to all the objects and accessed without using a particular object .that is the member belongs to the class as a whole rather than the object created from the class such members are called static members . Static variables and static methods are often referred as class variables and class methods in order to distinguish them from their counterparts instance variables and instance methods. Static variables are used when we want to have a variable common to all instance of a class. Ex: static int count; static int max(int x,int y) 20
  • 21. Defining and using static members Class mathoperation { static float mul(float x,float y) { return x*y; } static float divide(float x , float y) { return x/y; } } Class mathapplication { public static void main(string args[]) { float a= mathoperation.mul (4.0,5.0); float b= mathoperation.divide(a,2.0); System.out.println(“b=“+b); } } 21
  • 22. Method overloading In java it is possible to create methods that have the same name ,but different parameter lists and different definitions . This is called overloading . Method overloading is used when object are required to perform similar tasks but using different input parameters. this process is known as polymorphism. 22
  • 23. Class Room { Float length; Float breadth; Room (float x, float y) //constructor 1 { length=x; breadth = y; } Room (float x) //constructor 2 { int area( ) return (length*breadth) 23
  • 24. Inheritance :extending a class The mechanism of deriving a new class from an old one is called inheritance . The old class is know as base class or super class or parent class and new class is called subclass or derived class or child class. The inheritance allows subclass to inherit all the variable and methods of their parent classes. Inheritance may take different forms : single inheritance (only one super class) multiple inheritance (several super classes) hierarchical inheritance (only one super class , many subclasses) multilevel inheritance (derived from a derived class) 24
  • 25. Defining a subclass A subclass may be defined as follows: class subclassname extends supreclassname { variable declaration; methods declaration; } 25
  • 26. 26 class Room { int length; int breadth; Room (int x,int y) { length=x; breadth=y; area(); } int area( ) { return (length*breadth); } } class BedRoom extends Room { int height; BedRoom(int x,int y,int z) { super(x,y); height =z; } int volume() { return(length*breadth*height); } } public class InherTest { public static void main(String args[]) { BedRoom room1 = new BedRoom(14,12,10); int area1= room1.area(); int volume1=room1.volume(); System.out.println("Area="+area1); System.out.println("Volume="+volume1); } }
  • 27. Subclass constructor A subclass constructor is used to the instance variable of both the subclass and the super class . The subclass constructor uses the keyword super to invoke the constructor method of the super class . The keyword super is subject to the following condition :  super may only be used within a subclass constructor method.  The call to super class constructor must appear as the first statement within the subclass constructor .  The parameter in the super call must match the order and type of the instance variables in the super class. 27
  • 28. Overriding methods Method inheritance enables us to define and use method repeatedly in subclass without having to define the method again in subclass . At some occasions we want an object to respond to the same method but have different behavior when the method is called. This is possible by defining a method in the subclass that has the same name ,same argument and same return type as a method in the super class . Then when the method is called the method defined in the subclass is invoked and executed instead of the one in the super class . This is know as overriding. 28
  • 29. 29 class Super { int x; Super(int x) { this.x=x; } void display() { System.out.println("Super x="+x); } } class Sub extends Super { int y ; Sub(int x,int y) { super(x); this.y=y; } void display() { System.out.println("Super x="+x); System.out.println("Sub y="+y); } } public class OverrideTest { public static void main(String args[]) { Sub s1= new Sub(100,200); s1.display(); } } Output: Super x=100 Sub y=200
  • 30. 30 The this Keyword  The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields.  Another common use of the this keyword to enable a constructor to invoke another constructor of the same class.
  • 31. The this keyword is the name of a reference that refers to a calling object itself. One of its common uses is to reference a class’s hidden data fields. For example, a data-field name is often used as the parameter name in a set method for the data field. In this case, the data field is hidden in the set method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed simply by using the ClassName.StaticVariable reference. A hidden instance variable can be accessed by using the keyword this, as shown in next example 31
  • 32. 32 Reference the Hidden Data Fields public class Foo { private int i = 5; private static double k = 0; void setI(int i) { this.i = i; } static void setK(double k) { Foo.k = k; } } Suppose that f1 and f2 are two objects of Foo. Invoking f1.setI(10) is to execute this.i = 10, where this refers f1 Invoking f2.setI(45) is to execute this.i = 45, where this refers f2
  • 33. The this keyword gives us a way to refer to the object that invokes an instance method within the code of the instance method. The line this.i = i means “assign the value of parameter i to the data field i of the calling object.” The keyword this refers to the object that invokes the instance method set I, as shown in Figure 10.2(b). The line Foo.k = k means that the value in parameter k is assigned to the static data field k of the class, which is shared by all the objects of the class. 33
  • 34. 34 Another common use of the this keyword is to enable a constructor to invoke another constructor of the same class. For example, you can rewrite the Circle class as follows:
  • 35. Final variables and methods All method and variables can be overridden by default in subclasses . If we wish to prevent the subclasses from overriding , we can declare them as final using the keyword final as a modifier . Example : final int SIZE =100; final void showstatus() { } 35
  • 36. Final classes Sometimes we may like to prevent a class being further subclasses for security reasons . A class that cannot be is called a final class . This is achieved in java using the keywords final as follows: final class Aclass (…) final class Bclass extends Someclass(…) Declaring a class final prevent any unwanted extension to the class. 36
  • 37. Finalizer methods Java supports a concept called finalization , which is just opposite to the initialization . The finalizer method is simply finalize( ) and can be added to any class . java calls that method whenever it is about to reclaim the space for that object . The finalize method should explicitly define the task to be performed. 37
  • 38. Abstract classes and methods  In java we can do something which is just opposite to final that is we can indicate that a method must always be redefined in a subclass , thus making overriding compulsory .  This is done using the modifier keyword abstract in the method definition Example: abstract class Shape { ……………. ……………. abstract void draw(); ……………… } when a class contains one or more abstract method it should be declared abstract as in above given example. 38
  • 39.  While using the abstract class we must satisfy the following condition :  We can not use abstract classes to instantiate object directly.  The abstract methods of an abstract class must be define in its subclass .  We cannot declare abstract constructor or abstract static methods. 39
  • 40. Visibility control  Public Access Any variable or method is visible to the entire class in which it is defined but if we want to make it visible to all the classes outside this class we need to declare that variable or method as public . Example: public int number ; public void sum( ) { …………. } 40
  • 41. Friendly access  Some times we do not use public modifier ,yet they are still accessible in other classes in the program .  When no access modifier is specified the member defaults to a limited version of public accessibility is known as “friendly ” level of access .  The difference between the “public” access and the “friendly” access is that the public modifier makes field visible in all classes , regardless of their packages while the friendly access makes fields visible in same package, but not in other packages.  (A package is group of classes stored separately .)  A package in java is similar to a source file in “C”. 41
  • 42. Protected access  The visibility level of a “protected ” field lies in between the public access and friendly access. that is the protected modifier makes the field visible not only to all classes and subclasses in the same package but also to subclasses in other packages . the non-subclasses in other package cannot access the “protected ” members. 42
  • 43. Private access  private field enjoy the highest level degree of protection .  They are accessible only within their own class . They cannot be inherited by subclasses and therefore not accessible in subclasses .  A method declares as private behaves like a method declared as final .  It prevent the method from being sub classed . 43
  • 44. Private protected Access A field can be declared with two keywords private and protected together like private protected int x ; this gives a visibility level in between the “protected” access and private access . This modifier makes the field visible in all subclasses regardless of what package they are in . But these fields are not accessible by other classes in the same package . 44