0% found this document useful (0 votes)
5 views113 pages

Chapter 2

The document provides an overview of defining classes and methods in Java, emphasizing the structure, syntax, and conventions for creating classes, attributes, and methods. It discusses the use of multiple classes for better modularity and maintainability, as well as the importance of access modifiers and method parameters. Additionally, it covers key concepts such as static attributes, variable scope, the 'this' reference, and method overloading.

Uploaded by

artkaine lopero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views113 pages

Chapter 2

The document provides an overview of defining classes and methods in Java, emphasizing the structure, syntax, and conventions for creating classes, attributes, and methods. It discusses the use of multiple classes for better modularity and maintainability, as well as the importance of access modifiers and method parameters. Additionally, it covers key concepts such as static attributes, variable scope, the 'this' reference, and method overloading.

Uploaded by

artkaine lopero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

CATANDUANES STATE UNIVERSITY

COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

MARCH 1, 2025
DEFINING CLASS
A class--the basic building block of an object-oriented
language such as Java--is a template that describes the data
and behavior associated with instances of that class.

When you instantiate a class, you create an object that looks


and feels like other instances of the same class.

The data associated with a class or object is stored


in variables; the behavior associated with a class or object is
implemented with methods. Methods are similar to the functions
or procedures in procedural languages such as C.
Declaring Classes
Syntax:
[modifier] class className {
attribute declaration
constructor declaration
method declaration
}
Modifier
Optional
Can be keywords, abstract/final, and public
Coding Conventions

Class names should be:


Nouns, in mixed case with the first letter of each internal word capitalized.
BankTransaction, UserAccount

The filename should have the same name as your class.


Strictly speaking, the filename should have the same name as the public class in
your file.
Declaring Attributes

Syntax:
[modifier] type name [=default_value];

Where:
Modifier – optional, can be public, private, protected, final, static
Type – can be a class name or a primitive data type
Name – any valid identifier
Default value – optional initial value
Example of Declaring Attributes
private boolean isReady;
final String message = “Hello”;
int x = 10;

You can declare multiple attributes in a single line:


Date birthday, christmasDay;

public class BankAccount {


float balance;
String name;
long number;
}
Coding Conventions
• Declare all your attributes on the top of the class declaration.
• Variables’ first letter should be lower case.
• Internal words should start with a capital letter.
• Use an appropriate data type for each attribute you declare.

Static Attributes
• Class variables
• Allocated once regardless of how many objects are created.
• Can be accessed even without creating an object
ClassName.staticAttribute
amt = BankAccount.minBalance;

• To declare an attribute to be static, use the static modifier.


static float minBalance = 20000.00f;
Static Attributes
Declaring Methods
To declare methods we write,
[modifier] returnType name (parameterList) {
//method body
}

Were
modifier – can carry a number of different modifiers
returnType – can be any data type (including void)
name – can be any valid identifier
parameterList – list of parameters separated by commas. Each item in the
parameter list should have the form: type parameterName
Methods name should be in camel case as a convention
Parameters and Arguments,
Methods, Constructor
Return Values
To return a value

Simply put the value (or an expression that calculates the


value) after the return keyword.

The data type of the value returned by return must match


the type of method’s declared return value.

When a method’s return value is declared void, use the


form of return that doesn’t return the value.

For example,
return;
Getter Methods
Used to read values from our attributes (instance/static)
Returns the value of an attribute using the return keyword.
Usually written as: getNameOfAttribute()
Example:
Class BankAccount {
String name;
:
String getName() {
return name;
}
}
Setter Methods
Used to write or change values of attributes
Written as: setNameOfInstanceVariables(newValue)
The parameter’s type should be the same as the attribute
being modified.
Always returns void
Example:
Class BankAccount {
String name;
:
void setName (String newName) {
name = newName;
}
}
Multiple return Statements
You can have multiple return statements for a method as long as they are not on
the same block
You can also use constants to return values instead of variables

String getNumberInWords(int num) {


String defaultNum = “some other number”;
if (num == 1) {
return “one”; //return a constant
}
else if (num == 2) {
return “two”; //return a constant
}
//return a variable
return defaultNum;
}
Static Methods
Class methods
Declared using the static modifier
Class BankAccount {
float balance = 0;
String name;
long number;
static float minBalance = 20000;

static float getMinBalance() {


return minBalance;
}
}
Common Pitfall (Error)
NOTE: Static methods are not allowed to use non-static features of their class

Class MyClass {
int num = 0;

public static void main(String[] args) {


System.out.println(num);
}
}
Variable Scope
The scope
Determines where in the program the variable is accessible.
Determines the lifetime of a variable or how long the variable can
exist in memory.
The scope is determined by where the variable declaration is
placed in the program.

To simplify things, just think of the scope as anything between the


curly braces {…}. The outer curly braces are called inner blocks.
Variable Scope
A variable’s scope is
Inside the block where it is declared, starting from the point where it is declared, and in the
inner blocks.

Class MyClass {
int a;

void myMethod() {
int b;
//some code
}
}
Variable Scope Example
class MyClass {
void myMethod(int arg) {
for (int i=0; i<arg; i++) {
//some code
}

if (true) {
int j = 10;
//some code
}
}
}
Scope of a Variable
When declaring variables, only one variable with a given
identifier or name can be declared in a scope.
That means that the following declaration will result to an error:
{
int test = 10;
int test = 20;
}
Attributes Vs. Local Variables
Attributes
Declared within the class scope
Automatically initialized

Local Variables
Declared within the method
Requires explicit initialization
Common Pitfall
Using an uninitialized local variable will cause an error.

class MyClass {
int a;

void myMethod() {
int b;
System.out.println(b);
}
}
this REFERENCE

A special object reference referring to the object being operated on.

Used to differentiate an object’s method parameters from its


attributes.

To use the this reference, we type,


this.attribute

You can also use the this reference if you want to pass the
calling instance as a parameter to a method.
this REFERENCE
Example
class BankAccount {
int number;

void setNumber(int number) {


this.number = number;
}
}
this REFERENCE

You can also use the this reference if you want to pass the
calling instance as a parameter to a method.
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
Defining and using a multiple class

Java is a widely used programming language and


is one of the most popular languages for
developing applications. It’s an object-oriented
language that uses multiple classes, which can be
very useful for developing complex applications.
What is Multiple Class?
A Java multiple class refers to a program that contains two
or more related Java classes, enhancing modularity,
reusability, and maintainability in object-oriented
programming (OOP). These classes may share common
data or methods, helping to break down complex programs
into manageable components while avoiding naming
conflicts. Additionally, multiple classes can be structured in
a hierarchy using inheritance, allowing child classes to
inherit common attributes and methods from a parent
class. This reduces redundant code and simplifies
maintenance.
Benefits using of Multiple Class?
Using multiple classes in Java enhances code organization,
readability, and efficiency by logically separating program
components. It allows for faster execution, as each class can
be optimized independently. This approach improves
modularity, making it easy to add or remove code without
affecting other parts of the program—especially useful for
large applications. Additionally, multiple classes reduce
code duplication, enabling code reuse and minimizing
debugging efforts. This also enhances maintainability, as
changes in one class can be efficiently propagated to
others.
How to Declare a Multiple Class?
Multiple classes can be declared using the keyword ‘class’.
For example, if a program contains two classes, Foo and Bar,
they would be declared as follows:

public class Foo {


...
}

public class Bar {


...
}
How to Declare a Multiple Class?
Multiple classes can be declared in a single file using the
keyword ‘class’. In this case, each class would be declared
using the same syntax as before, but the classes would be
separated using braces.

public class Foo {


// Main class (must match filename)
}

class Bar {
// Secondary class
}
Note:
When declaring multiple classes in a single file, it is
important to note that the classes must be declared in the
same order as they are used in the program. This is because
the compiler reads the classes in the order they are
declared, and if the classes are not declared in the correct
order, the program will not compile correctly.
Accessing Member Variables
When two or more classes are defined in a Java program,
member variables can be accessed across those classes.
This can be done using either the public or protected
keywords to indicate the visibility of the variable. If a variable
is declared as public, then it can be accessed from any
other class in the program; however, if it is declared as
protected, then it can only be accessed from within its own
class or from subclasses.
Accessing Member Variables
Member variables can be accessed across classes using
visibility modifiers:

• public: Accessible from any class.


• protected: Accessible within its class and subclasses.
• private: Accessible only within its own class.

When accessing variables across classes, scope matters. A


private variable remains restricted to its class, while a static
variable can be accessed from any class without creating
an instance.
Calling Methods Across Classes
Java provides several different ways to call methods across
class boundaries. The most straightforward way is to use the
class’s public methods, which can be called from any class
in the program. The other way is to use inheritance, which
allows methods from one class to be called from another
class that inherits from it.

Using Public Methods – A method declared as public in one


class can be accessed by another class through an
instance of the first class.
Extending a class
A subclass is a class that inherits from a parent (superclass)
and adds its own methods and variables. It can be used in
place of the parent class when creating objects.

Key Considerations When Extending a Class:


1. Overriding Methods – If a subclass overrides a method
from the parent, it may change the original behavior
unexpectedly.
2. Dependency on Parent Class – Changes to the parent
class may need to be updated in the subclass to
maintain consistency.
Extending a class
When extending a class, it is important to consider the
implications of the changes being made. If the subclass
overrides any of the parent class’s methods, the behavior of
the parent class may be altered in unexpected ways.
Additionally, any changes made to the parent class may
need to be reflected in the subclass as well.
Activity

CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

Matching Arguments and Parameters


What is Argument?
An argument is a value passed to a function when the
function is called. Whenever any function is called during the
execution of the program there are some values passed
with the function. These values are called arguments. An
argument when passed with a function replaces with those
variables which were used during the function definition and
the function is then executed with these values.
Arguments are Passed by Value
◼ In Java, arguments are always passed by value.
◼ The method cannot change the caller's argument.
◼ A method can change the object the an argument references!
public void swap( int a, int b ) { // swap args
int temp = a;
a = b;
b = temp;
}
public static void main(String [] args) {
int a = 10; int b = 20;
swap( a, b );
System.out.println( "a = " + a );
// prints "a = 10"
What is Parameters?
Parameters are variables defined in the method declaration after the
method name, inside the parentheses. This includes primitive types such
as int, float, boolean, etc, and non-primitive or object types such as an
array, String, etc. You can pass values(Argument) to the method
parameters, at the method call.
Method Parameters
Pass data to methods using parameters.

public void deposit( long amt ) {


balance += amt; }
access type of parameter(s)
return value

Actual argument type must be compatible with parameter:


BankAccount acct = new BankAccount();
int a = 1000;
long b = 1000000L;
acct.deposit( a ); // OK ... argument type matches parameter
acct.deposit( b ); // OK ...but why?
acct.deposit( 50.25 ); // ERROR ... incompatible type
Method Parameters

Method Parameters, again


◼ Both the number and type of argument must match the
method signature.
// overloaded method:
int max(int m, int n) { . . . }
float max(float x, float y) { . . . }
float max(float x, float y, float z) { . . . }

◼ Which "max" method will be called?


int r = max( 20, 45 );
float q = max( 20, 33.F); // mixed arguments
float z = max(1, 2, 3.5F); // mixed arguments
int p = (int) max( 2 , -9.3F );
Parameters Passing
Pass by Value ("call by value") means a function gets a copy of
the caller's arguments. Changes to the copy to not effect the
caller.
Pass by Reference ("call by reference") means that the function
parameters refer to the same storage used by the caller's
arguments.
Java always uses "pass by value".
◼ a method cannot change values of the caller's arguments
◼ a method can change the object that a parameter refers to (this

change effects the caller's data)


Take note:
◼ The actual number of parameters may be zero.
◼ Be careful for zero-length array.
double max = MyMath.max( ); // stupid but legal

◼ To avoid empty parameter list, add a required param:

public static double max( double first,


double ... x )
{
double max = first;
for (int k=0; k<x.length; k++)
if (x[k] > max) max = x[k];
Rules for Variable Length Parameter
◼ Can only have 1 variable length param per method.
◼ Must be last parameter in method signature.

double power( double ... x, int ... y ) // ERROR

void addMany( List list, String ... item) // OK

void addMany(String ... item, List list) // ERROR


CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

Methods and Overloaded Methods


What is Method?

• A collection of statements that are group together to perform an


operation.
• A method has the following syntax:

modifier return_Value_TypeMethod_Name(list of parameters){

// Method body;
}
Parts of Method

1. Modifiers:
➢ Tells the compiler how to call the method
➢ Defines the access type of the method

2. Return Types:
➢ The data type of the value the method returns
➢ The return type void when no value is returned
Parts of Method

1. Modifiers:
➢ The actual name of the method
➢ Method name and the parameter list together constitute
the method signature

2. Return Types:
➢ When a method is invoked, a value is passed to
parameter
➢ This value is referred to as actual parameter or argument
➢ The parameter list refers to the type, order, and number of
the parameters.
Parts of Method

1. Modifiers Body
➢ The method body contains a collection of statements that
define what the method does
Method Overloading

Method overloading is a fundamental concept in Object-


Oriented Programming (OOP) that enhances code readability
and reusability. It allows multiple methods in a class to have
the same name but with different parameter lists (differing in
number, type, or sequence). This enables programmers to
define multiple behaviors for a method name without creating
separate method names, making the code cleaner and more
intuitive.
Method Overloading

➢ Method with same name but different behavior


➢ Method with same but different method signature
➢ Overloaded methods may or may not have different return type
but it should have different arguments(s)
▪ int test () {}
▪ int test (int a) {}
▪ int test (double a) {}
▪ int test (double a, int a) {}
Code Example
Characteristics of Method Overloading

1. Same Method Name: All overloaded methods must have


the same name.
2. Different Parameter Lists: Overloaded methods must
differ in at least one of the following:
• Number of Parameters – Methods can have a different
count of arguments.
• Type of Parameters – Methods can differ based on
parameter data types.
• Order of Parameters – A different sequence of data
types in the parameters can differentiate methods.
Characteristics of Method Overloading

3. Return Type Does Not Matter: Changing the return type


alone does not count as method overloading.

4. Compile-Time Polymorphism: Overloading is an example of


static polymorphism because the method to be executed
is determined at compile time.
Different Ways of Method Overloading

1. Changing the Number of Parameters

Method overloading can be achieved by changing the


number of parameters while passing to different
methods.
Different Ways of Method Overloading

2. Changing Data Types of the Arguments

Methods can be considered Overloaded if they have


the same name but have different parameter types,
methods are considered to be overloaded.
Different Ways of Method Overloading

3. Changing the Order of the Parameters of Methods

Method overloading can also be implemented by


rearranging the parameters of two or more overloaded
methods. If the parameter types are different, changing
their order can create unique method signatures.
Different Ways of Method Overloading
3. Changing the Order of the Parameters of Methods
Always remember that overloaded methods have the
following properties:
The same name
Different signature
•Signature – order, number, and types of arguments
•Examples:
int method(int x, float y)
int method(float x, int y)
int method(int x, float y, int z)
int method(int a, float b)
Return types can be different or the same
Method Overriding
➢ The child class provides alternative implementation for
parent class method.
➢ The key benefit of overriding is the ability to define
behavior that’s specific to a particular subclass type.
➢ Overridden method: In the superclass.
➢ Overriding method: In the subclass
Example of Method Overriding
Method Overriding
Rules for Method Overriding
Rules for Method Overriding
Rules for Method Overriding
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

Constructors
What is Constructors?

A constructor in Java Programming is a block of code that


initializes (constructs) the state and value during object
creation. It is called every time an object with the help of a
new () keyword is created.
Constructors

• Constructor in java is used to create the instance of the


class.
• Constructors are almost similar to methods except for two
things – it’s name is same as class name and it has no
return type.
• Constructor Types:
✓ Default Constructor
✓ No-Args Constructor
✓ Parameterized Constructor
Constructors

• Special method that is executed when an object is created.


• Called in conjunction with the new operator
• Rules in writing constructors:
➢ Constructors must have the same name as the class
➢ Constructors do not specify a return type
➢ Constructors can be overloaded.
Example: the String class
public String();
public String(String val);
public String(char val[]);
Constructors

• Special method that is executed when an object is created.


• Called in conjunction with the new operator
• Rules in writing constructors:
➢ Constructors must have the same name as the class
➢ Constructors do not specify a return type
➢ Constructors can be overloaded.
Example: the String class
public String();
public String(String val);
public String(char val[]);
Declaring Constructors

• To declare a constructor, we write

[modifier] ClassName (parameterList) {


//constructor body
}
Default Constructors

• Is the constructor without any parameters


• If the class does not specify any constructors, then an
implicit default constructor is created with no parameters
• If the class has at least one constructor, the default
constructor is no longer provided.
- You have to explicitly create one if you need it.
Overloading Constructors
Overloading Constructors
this() CONSTRUCTOR CALL

• You can use this() to call another constructor from within a


constructor.

• Rules:
✓ When using the this() constructor call, it must be the
first statement in a constructor.
✓ It can only be used in a constructor definition.
this() CONSTRUCTOR CALL
FINALIZERS

• Special method for “cleaning up” purposes


- Closing files, sockets, database connections, etc.
• Rules
➢ Must be declared as finalized()
➢ Always returns void
➢ Only one finalizer per class
• Not called explicitly
• Called by Java Runtime before the object is collected by the
garbage collector.
FINALIZERS EXAMPLE
• class DataAccessObject {
• Connection conn;

• DataAccessObject() {
• conn = DriverManager.getConnection();
• }
• …
• public void finalize() {
• conn.close();
• //perform cleanup procedures
• }
• }
Enum TYPES
To declare a class with attributes representing days of the week

public class Day {


static int SUNDAY = 1;
static int MONDAY = 2;
static int TUESDAY = 3;
static int WEDNESDAY = 4;
static int THURSDAY = 5;
static int FRIDAY = 6;
static int SATURDAY = 7;
}
Enum TYPES
This makes our code more readable.
For example:
int someday = Day.MONDAY;
Is more readable than:
int someday = 2.

This, however is not type safe. For example, nothing prevents you from writing:
int someday = 99; // No error

Printed values are not informative.


System.out.println(someDay); // 2
Enum TYPES
• An enum type is a type whose fields consist of a fixed set of constants.
• Defined by using enum keyword.
• Introduced in Java 5 only.
• By convention, fields in an enum type are written in all uppercase letters.

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Enum TYPES
• Enum types enforce compile time type safety.

Example:
Day today = Day.Monday;
Day anotherDay = 2; // ERROR

• Printed values are also informative.

System.out.println(today); // MONDAY
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

Organizing Classes into Package


What is Packages?

• A Java package is a set of classes, interfaces, and sub-


packages that are similar. In Java, it divides packages into
two types: built-in packages and user-defined packages.
Built-in Packages (packages from the Java API) and User-
defined Packages are the two types of packages (create
your own packages). Provides for a convenient
mechanism for managing a large group of classes and
interfaces while avoiding potential naming conflicts.
What is Packages?

• A set of classes and interfaces grouped together are


known as Packages in JAVA. The name itself defines that
pack (group) of related types such as classes, sub-
packages, enumeration, annotations, and interfaces that
provide name-space management. Every class is a part of
a certain package. When you need to use an existing class,
you need to add the package within the Java program.
What is the used of Packages?

The benefits of using Packages in Java are as follows:

• The packages organize the group of classes into a


single API unit
• It will control the naming conflicts
• The access protection will be easier. Protected and
default are the access level control to the package
• Easy to locate the related classes
• Reuse the existing classes in packages
Importing Packages
• To use classes in other packages, you need to import the package of those
classes.
• Use the import statement.
• The java.lang package is implicitly imported.
That is why you can use classes like String and Integer inside the
program even though you haven’t imported any package.

• The syntax for importing packages is as follows:


• import nameOfPackage.ClassName;

• If you want to import all classes in a package, use * in place of the


ClassName.
• import nameOfPackage.*;
Import One Specific Class From a
Package

import java.util.scanner

In the above program, you have included only one scanner


class from util subpackage. It will get the user value and
display.
Import One Whole Package

import java.util.*

In the above program, the * denotes all the classes from the
util package. Along with other classes, it loads the date class
as well. The date class displays the current date and time.
Importing Packages
These two are essentially the same.
import java.util.Date;
import java.lang.*;

class Appointment {
Date when;
String where;
}
______________________________________________________
class Appointment {
java.util.Date when;
String where;
}
Use Complete Qualified Name

java.net.InetAddress
ipAddress=java.net.InetAddress.getLocalHost();

The InetAddress class is available in the java.net package,


without using the import keyword. Directly call the
InetAddress class with the complete package name
java.net.InetAddress. This will get the IP address.
Guide in Creating Java Packages
To create a package, you should be aware of the Java file
system directory. This is similar to the files and folders
organized on your computer. You need the help of the
keyword “package” to create your own package. The
declaration of the package should be the first statement
before any import statements in the Java class.

Before creating your own package, you need to keep in mind


that all the classes should be public so that you can access
them outside the package.
Declaring Packages
To declare your own package, the syntax is:
package packageName;

Packages can also be nested. In this case, the Java


interpreter expects the directory structure containing the
executable classes to match the package hierarchy.

package packageName.subpackage;
Coding Conventions
The three top-level elements must appear in the following
order:
• Package declaration
• Import statements
• Class definitions
Class path variable and how classes are
found
• Tells the Java compiler where to look for packages, not
classes.
• Assuming your working directory is C:\321, and you
have a BankAccount class in the package com.banco

C:\321 must be included in the class path

The full path to BankAccount.class must be


C:\321\com\banco\BankAccount.class
Setting the class path variable in windows

To set the CLASSPATH variable in Windows,


• Open the Control Panel
• Open the System Applet
• Go to Advanced Tab
• Click on Environment Variables
Setting the class path variable in DOS

To see your current CLASSPATH, type


C:\321> echo %CLASSPATH%

To add C:\321 to the CLASSPATH, type


C:\321\ set CLASSPATH=%CLASSPATH%;C:\321

To add the current directory to the CLASSPATH, type


C:\321> set CLASSPATH=%CLASSPATH%;.
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods

Local and Class Variables


What is variables?

variables are fundamental elements used to store data


that can be manipulated throughout a program. A variable
is essentially a container that holds data that can be
changed during the execution of a program.
Variable Types

• Each variable in Java has a specific type, which


determines the size and layout of the variable’s memory.
• The range of values that can be stored within that
memory.
• Variable Declaration:

datatype variable = value;


datatype variable = value; variable = value,…;
Variable Types

• Example

int a, b, c; //Declares three int’s a, b, and c.


int a=10, b=10, c=20; //Example initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declare and assigns a value of PI.
char a = ‘a’; //the char variable a is initialized with value ‘a’
Types of variables

➢ Local Variables: Declared inside a method or block and


can only be accessed within that method or block.
➢ Instance Variables: Declared inside a class but outside
of any method. They are associated with an instance of
the class.
➢ Static Variables: Declared as static and are shared
among all instances of a class.
Variable Type – Local Variable
▪ It declared inside of methods, constructors, or blocks.
▪ Access modifier cannot be used for local variable.
▪ Local variables are visible only within the methods.
▪ Variable can be accessed when the method is called.

Class
{
method
{
declare variable
}
}
Example– Local Variable
Variable Type – Instance Variable
▪ It declare inside of a class but outside of methods.
▪ This variable can be access by any methods.
▪ By Creating object for a class, we can access this variable
from main methods.

Class
{
declare variable
method
{
// can use var
}
▪ }
Example– Instance Variable
Variable Type – Class/Static Variable
▪ Variable declared inside of class but outside of methods with
static keyword.
▪ Static variables are stored in the static memory.
▪ Static variables can be accessed by static methods or
constructors
Class
{
declare variable
constructor
{
// can use var
{
//can use var
}
}
Example– Class/Static Variable
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY

ITRACKC1

THANK YOU

You might also like