0% found this document useful (0 votes)
16 views

JAVA METHODS

Uploaded by

v28424976
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

JAVA METHODS

Uploaded by

v28424976
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JAVA CLASS, OBJECTS ‘N’ METHODS

KIT-501
CLASS IN JAVA

A class in Java is a set of objects which shares common characteristics/ behaviour


and common properties/ attributes. It is a user-defined blueprint or prototype
from which objects are created. Class is not a real-world entity. It is just a template
or blueprint or prototype from which objects are created. Class is a group of
variables of different data types and a group of methods.

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be physical.
COMPONENTS OF JAVA CLASSES
 MODIFIERS: A class can be public or has default access.

 CLASS KEYWORD: class keyword is used to create a class.

 CLASS NAME: The name should begin with an initial letter (capitalized by convention).

 SUPERCLASS(IF ANY): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.

 INTERFACES(IF ANY): A comma-separated list of interfaces implemented by the class, if


any, preceded by the keyword implements. A class can implement more than one
interface.

 BODY: The class body is surrounded by braces, { }.


SYNTAX TO DECLARE A CLASS
class <class_name>{
field;
method;
}

Here, fields (variables) and methods represent the state and behaviour of the
object respectively.
• Fields are used to store data
• Methods are used to perform some operations
JAVA OBJECTS
An object is called an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class. an object is created from a class.

An object has three characteristics:


• State: represents the data (value) of an object.

• Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

• Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to
the external user. However, it is used internally by the JVM to identify each object uniquely.

• An object is a real-world entity. The object is an entity which has state and behavior. An
object is a runtime entity.
EXAMPLE
//Defining a Student class.
class Student{
//defining fields
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
METHODS IN JAVA
• A method is a block of code or collection of statements or a set of code grouped together to perform a

certain task or operation. It is used to achieve the reusability of code.

• It also provides the easy modification and readability of code, just by adding or removing a chunk of code.

• The method is executed only when we call or invoke it. You can pass data, known as parameters, into a

method.

• A method in Java refers to a block of code that is associated with an object or a class. In object-oriented

programming (OOP), methods are functions that belong to a specific class or instance of that class.

• Methods are typically used to define the behaviour of objects and can access the instance variables of the

class.
METHOD DECLARATION
accessModifier returnType methodName(parameters) {
// Method body
// Code to perform a specific task
}
• accessModifier: Determines the visibility of the method (e.g., public, private,
protected, or package-private).
• returnType: Specifies the data type of the value that the method returns. Use void if
the method doesn't return any value.
• methodName: A unique name for the method within its class.
• parameters: A list of input parameters enclosed in parentheses. You can have zero or
METHOD EXAMPLE
public int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}

 public is the access modifier.


 int is the return type (it returns an integer).
 add is the method name.
 (int num1, int num2) are the parameters.
METHOD ATTRIBUTES
• METHOD SIGNATURE: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.

• ACCESS SPECIFIER: Access specifier or modifier is the access type of method. It specifies visibility of the method.

• RETURN TYPE: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

• METHOD NAME: It is a unique name that is used to define the name of a method. A method is invoked by its name.

• PARAMETER LIST: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.

• METHOD BODY: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.
ACCESS SPECIFIERS
Public: The method is accessible by all classes when we use public specifier in our
application.

Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
NAMING A METHOD
While defining a method, remember that the method name must be
a verb and start with a lowercase letter. If the method name has more than
two words, the first name must be a verb followed by adjective or noun. In
the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example:
• Single-word method name: sum(), area()

• Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name
in the same class, it is known as method overloading.
METHOD INVOCATION

• For using a method, it should be called. There are two ways in which a
method is called i.e., method returns a value or returning nothing (no
return value).

• To call a method in Java, write the method's name followed by two


parentheses () and a semicolon;

• The process of method calling is simple. When a program invokes a


method, the program control gets transferred to the called method.
METHOD INVOCATION
class Main {
// create a method
public static int square(int num) {

// return statement
return num * num;
}

public static void main(String[] args) {


int result;
// call the method
// store returned value to result
result = square(10);

System.out.println("Squared value of 10 is: " + result);


}
WAYS TO CREATE METHODS
There are two ways to create a method in Java:

1. INSTANCE METHOD: Access the instance data using the object name. Declared inside a class.
// Instance Method

void method_name(){

body // instance area

2. STATIC METHOD: Access the static data using class name. Declared inside class with static keyword.

//Static Method

static void method_name(){

body // static area

}
STATIC METHODS
• A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using the
keyword static before the method name.

• The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is invoked by using the class name. The best example of a static
method is the main() method.

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
INSTANCE METHOD
The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or

invoking instance method, it is necessary to create an object of its class.


public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
ABSTRACT METHOD
The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method.

Abstract methods in Java do not have any code in them. This means that there is no
need to provide the implementation code while declaring it. Instead, it is possible to
declare the method body later in the program.

There is another hard rule to declare abstract methods, and it is that they can only be
declared within an abstract class. It always declares in the abstract class. It means the
class itself must be abstract if it has abstract method.

It is known that one can declare an abstract method by using the “abstract” keyword.
// Abstract class public class Main {
abstract class Animal {
// Abstract method (no implementation) public static void main(String[] args) {
public abstract void makeSound();
// Creating instances of Dog and Cat
}
Animal dog = new Dog();
// Concrete subclass
class Dog extends Animal { Animal cat = new Cat();
@Override
public void makeSound() {
System.out.println("Dog barks"); // Calling abstract method makeSound() on both objects
} dog.makeSound();
}
cat.makeSound();
// Concrete subclass
}
class Cat extends Animal {
@Override }
public void makeSound() {
System.out.println("Cat meows");
}
}
METHOD OVERLOADING
• Java allows you to define multiple methods with the same name but
different parameter lists. This is called method overloading. Java
determines which method to call based on the number and types of
arguments provided.

• Method overloading in Java allows you to define multiple methods


with the same name in a class but with different parameter lists. Java
determines which method to call based on the number and types of
arguments passed during method invocation.
METHOD OVERLOADING RULES
METHOD NAME: The overloaded methods must have the same name.

PARAMETER LIST: The overloaded methods must have a different number of


parameters, or the parameters must have different types or different order.

RETURN TYPE: The return type can be different for overloaded methods. However,
the return type alone is not sufficient to distinguish overloaded methods.

ACCESS MODIFIERS AND EXCEPTIONS: Overloaded methods can have different


access modifiers (e.g., public, private, protected) and can throw different
exceptions.
EXAMPLE OF METHOD OVERLOADING
public class MathUtils {

public int add(int a, int b) {


return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String concatenate(String str1, String str2) {
return str1 + str2;
}
METHOD INVOCATION WITH OVERLOADED METHODS

When you call an overloaded method, Java determines which method to execute based on the number

and types of arguments you pass. Method overloading is a useful feature in Java because it allows you to

provide multiple ways to perform similar operations, making your code more readable and flexible.
MathUtils math = new MathUtils();

int result1 = math.add(5, 3); // Calls add(int a, int b)

double result2 = math.add(2.5, 3.5); // Calls add(double a, double b)

int result3 = math.add(1, 2, 3); // Calls add(int a, int b, int c)

String result4 = math.concatenate("Hello", " World"); // Calls concatenate(String str1, String str2)

In the code above, Java automatically selects the appropriate add method based on the argument types. Similarly, it
selects the concatenate method based on the argument types (strings in this case).

You might also like