SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 

Mais procurados (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Main method in java
Main method in javaMain method in java
Main method in java
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 

Destaque

class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
Sadhana28
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
rahulsahay19
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationships
Pooja mittal
 
Introduction To Uml
Introduction To UmlIntroduction To Uml
Introduction To Uml
guest514814
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 

Destaque (20)

class and objects
class and objectsclass and objects
class and objects
 
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
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
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
 

Semelhante a Object and class

Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
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
DeepVala5
 
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
 
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
archgeetsenterprises
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 

Semelhante a 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
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

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