Unit 5 1
Unit 5 1
&
METHODS
TOPICS TO COVER
Introduction.
Defining a class.
Creating Objects.
CREATE
OBJECTS
METHODS
DEFINING A CLASS
A class is a user-defined data type.
Variables and Functions can be created within
class
SYNTAX EXAMPLE
INSATNCE VARIABLES
class classname class area
{ {
field declaration; Declaring variables int side;
Instance variables are declared
int length;
exactly as LOCAL variables }
method declaration;
}
METHOD DECLARATION
Without methods class has NO LIFE.
Since objects created by such class cannot respond to any
messages.
Thus, methods are necessary for MANIPULATING DATA.
SYNTAX EXAMPLE
class area
type method-name(parameter list) {
{ int side;
int length;
void get(int s, int l)
}
{
side = s;
length = l;
Type of the value the method returns. It can be }
void, int, float, double }
EXAMPLE FOR CREATING CLASSES
.
objectname.methodname(parameter-list); a1 get (10, 15);
a1.tri();
a1.square();
}
Constructors
Method Overloading
Constructor Overloading
Nesting of methods
JAVA allows objects to initialize themselves when they are
created CONSTRUCTOR
PROPERTIES:-
• Initializes an object immediately upon creation.
• Same name as the class in which it resides and syntactically similar
to a method.
• Is called automatically after the object is created.
• Does not have return type.
EXAMPLE
NO RETURN TYPE
OUTPUT
Methods have same name, but different parameter list .
Is used when objects are required to perform similar tasks but
using different input parameters.
Also known as POLYMORPHISM.
Here, the aim is to provide several method definitions all with
same name, but different parameter lists.
The difference may either in number or type of arguments
Method’s return type does not play any role in this
In addition to overloading methods, you can also
overload constructor method
EXAMPLE
A method of a class can be called only by an
object of that class using dot operator.
Thus member belongs to the class as a whole rather than the objects
class.
SYNTAX:-
static int count; STATIC MEMBERS
Referred to as
static int max(int x, int y)
Class variables and Class methods
EXAMPLE
RESTRICTIONS FACED BY STATIC
METHODS:-
STATIC
METHODS ARE
CALLED USING
CLASS NAME
EXAMPLE
CALL by VALUE vs. CALL by REFERENCE
REMEMBER
CALL by VALUE:- Simple
type arguments are passed
to methods.
CALL by REFERENCE:-
Objects are passed to
methods
RECURSION
terms of itself.
Visibility
Labels
PUBLIC PROTECTED
PRIVATE
VISIBILITY CONTROL (Contd..)
PUBLIC
PROTECTED ItsFriendly
level lies between PUBLIC ACCESS & FRIENDLY
ACCESS.
Makes fields visible in all Makes
Makesthefields
fieldsvisible
visibleonly
not only
in to all classes and
classes, regardless of their subclasses
the samein same package but also to subclasses in
package.
packages other packages