0% found this document useful (0 votes)
2 views35 pages

java3

This document provides an overview of methods and object-oriented programming in Java, detailing the structure and types of methods, including predefined and user-defined methods, method overloading, and recursion. It also explains key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it covers access modifiers and constructors, emphasizing their roles in defining the visibility and initialization of class members.

Uploaded by

raavansohan
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)
2 views35 pages

java3

This document provides an overview of methods and object-oriented programming in Java, detailing the structure and types of methods, including predefined and user-defined methods, method overloading, and recursion. It also explains key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it covers access modifiers and constructors, emphasizing their roles in defining the visibility and initialization of class members.

Uploaded by

raavansohan
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

JAVA Module – 2

Classes, Objects and


Methods
By
Ashish Kumar
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.
We write a method once and use it many times.
The method is executed only when we call or invoke it.
The most important method in Java is the main() method.
Method Declaration
Public int sum(int a, int b)
{
// Body of the method
}
Here, SUM is a method name, a and b are the parameters, int is the
return type, and public is the access specifier.
Methods in Java
Access Specifier:
Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access
specifier:
1. Public: The method is accessible by all classes when we use public
specifier in our application.
2. Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
3. Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
4. 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.
Methods in Java
Return Type: Return type is a data type that the method returns. 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.
Note- Use camel notation for naming the method.

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, the parentheses is
left blank.

Method Body: It contains all the actions to be performed. It is


enclosed within the pair of curly braces.
Methods in Java
 Types of Method
There are two types of methods in Java:
1. Predefined Method:
 Predefined methods are those methods that are already defined in
the Java class libraries.
 It is also known as the standard library method or built-in method.
 We can directly use these methods just by calling them in the
program at any point.
 Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc.
 When we call any of the predefined methods in our program, a series
of codes related to the corresponding method runs in the background
that is already stored in the library.
Methods in Java
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
} }

2. User-defined Method:
The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
Methods in Java
import [Link];
public class EvenOdd
{
public static void main (String args[])
{
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
int num=[Link]();
findEvenOdd(num);
}
public static void findEvenOdd(int num)
{
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
}
 Note – A static method can only call another static method.
Methods in Java
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
[Link]("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
} }

 Note – A static method can only call another static method.


Methods in Java
Static Method
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.

The best example of a static method is the main() method


Methods in Java
public class Addition
{
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
[Link]("The sum of a and b is= " + c);
}
}
Methods in Java
public class Addition{
int add(int n1, int n2){
int s;
s=n1+n2;
return s;
}
public static void main(String[] args) {
int a = 19;
int b = 5;
Addition obj = new Addition();
int c = [Link](a,b);
[Link](c);
}
}
Methods in Java
Method Overloading
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 Method overloading increases the readability of the program.

There are two ways to overload the method in java


1. By changing number of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Methods in Java
2. By changing the data type
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
Methods in Java
Can we overload main method?
By method overloading, we can have any number of main methods in a class.
But JVM calls main() method which receives string array as arguments only.

class TestOverloading4{
public static void main(String[] args)
{
[Link]("main with String[]");
}
public static void main(String args)
{
[Link]("main with String");
}
public static void main()
{
[Link]("main without args");
}
}
Methods in Java
 Variable Arguments (Varargs)
 Variable Arguments (Varargs) in Java is a method that takes a variable number of
arguments.
 Variable Arguments in Java simplifies the creation of methods that need to take a
variable number of arguments.
 It can avoid method overloading.

 Syntax of Varargs
 Varargs method is implemented by using the single dimensions arrays concept.
 A variable-length argument is specified by three periods or dots(…).
public static void fun(int ... a)
{
// method body
}
Here, fun( ) can be called with zero or more arguments.
Methods in Java
class Test1 {
static void fun(int... a)
{
[Link]("Number of arguments: " + [Link]);
// using for each loop to display contents of a
for (int i : a){
[Link](i + " ");
}
}
public static void main(String args[])
{
fun(100);
fun(1, 2, 3, 4);
fun();
}}
Methods in Java
 Recursion
 The process in which a function calls itself directly or indirectly is called recursion .
 Using recursive algorithm, certain problems can be solved quite easily.

 All recursive algorithms must obey three important laws:


1. A recursive algorithm must have a base case.
2. A recursive algorithm must change its state and move toward the base case.
3. A recursive algorithm must call itself, recursively.

Example: Factorial of a number


// if(n = = 1||n==0){return 1}
//factorial(n) = n*factorial(n-1)
Object-oriented Programming
In the Java programming language, an object is a single instance of a
class.
A class is a template for creating objects. It defines the data and
behavior of a type.

For example, consider a class called "Dog".

This class might define the data for a dog, such as its breed, size, and
name, as well as its behavior, such as barking and wagging its tail.

An object of the "Dog" class would be a specific dog, such as a


Labrador Retriever named "Buddy".
Object-oriented Programming
public class Dog {
// Data (instance variables)
private String breed;
private int size;
private String name;
// Behavior (methods)
public void bark()
{
[Link]("Bark!");
}
public void wagTail()
{
[Link]("Wag!");
}
}
Object-oriented Programming
To create an object of the "Dog" class, "new" operator is used:
Dog buddy = new Dog("Labrador Retriever", 70, "Buddy");

This creates a new "Dog" object with a breed of "Labrador Retriever",


a size of 70, and a name of "Buddy".

Methods on the object can be called as:


[Link](); // Outputs "Bark!"
[Link](); // Outputs "Wag!"
Object-oriented Programming
Object-oriented programming (OOP) is a programming paradigm that
is based on the concept of "objects", which can contain data and code
that manipulates that data.
Some of the key features of OOP are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Object-oriented Programming
Abstraction: It refers to the ability to focus on the essential features of an
object and ignore the details of its implementation.
It allows the programmer to think in terms of the "what" rather than the
"how" when it comes to using objects in their code.
Example:
 Imagine you have a class called "Shape" that represents different shapes
that can be drawn on a screen. The Shape class might have a method called
"draw()" that is used to draw the shape on the screen.
 Now, you might have several different subclasses of Shape, such as Circle,
Square, and Triangle, each of which has its own implementation of the
"draw()" method that specifies how to draw the specific shape.
 From the perspective of the programmer using the Shape class, they don't
need to know the details of how each specific shape is drawn.
 They can simply create a new Shape object and call its "draw()" method, and
the correct implementation will be called based on the specific type of
shape that was created.
Object-oriented Programming
Encapsulation: It refers to the bundling of data and the methods that
operate on that data within a single unit, or object.
This is meant to reduce complexity and increase modularity by allowing the
programmer to think in terms of objects, rather than individual variables and
functions.
Example:
 Imagine you are writing a program to model a bank account. You might
create a class called "Account" that has instance variables for the account
balance, account number, and account holder name.
 You might also create methods for depositing money, withdrawing money,
and checking the balance of the account.
 By encapsulating all of this data and behavior within the Account class, you
can think of an account as a single, self-contained unit, rather than having to
keep track of separate variables and functions for each piece of data.
 This makes the code easier to understand and maintain, because you can
focus on the actions that an account can perform, rather than worrying
about the details of how those actions are implemented.
Object-oriented Programming
 Inheritance: It refers to the ability to create new objects that are built upon existing
objects, and to specify how the new objects should differ from the existing ones.
 This is meant to reduce duplication of code and allow for more efficient code reuse.

Example:
 Imagine you have a base class called "Vehicle" that represents any type of vehicle.
This class might have instance variables for the number of wheels, the number of
doors, and the current speed of the vehicle. It might also have methods for starting
the engine, accelerating, and braking.
 Now, suppose you want to create a subclass of Vehicle called "Car" that represents a
specific type of vehicle. You can use inheritance to create the Car class, which will
automatically have all of the features of the Vehicle class, as well as any additional
features that are specific to a car, like number of seats in the car, and a method for
honking the horn.
 This allows you to create more complex programs more efficiently, because you don't
have to start from scratch for each new type of object that you want to create.
Object-oriented Programming
Polymorphism: It refers to the ability to create a single interface to be
used with multiple different implementations.
This allows for flexibility in the design of a program, as well as the
ability to easily add new implementations in the future.
Object-oriented Programming
Create a new class
class <class_name>{
field;
method;
}
Example :
public class Employee {
int id; // Attribute 1
String name; // Attribute 2
}

Note – In a java program, there can be only one public class.


Object-oriented Programming
class Employee{
int id;
String name;
}
public class Main {
public static void main(String[] args) {
Employee hari = new Employee();
Employee ritik = new Employee();
[Link] = 12;
[Link] = “HariOm";
[Link]([Link]);
[Link]([Link]);
}}

Note – In a java program, there can be only one public class.


Object-oriented Programming
class Employee{
int id;
String name;
public void printDetails(){
[Link]("My id is " + id);
[Link]("and my name is "+ name);
}
}
public class Main {
public static void main(String[] args) {
Employee hari = new Employee();
Employee ritik = new Employee();
[Link] = 12;
[Link] = “HariOm";
[Link] = 12;
[Link] = “HariOm";
[Link]();
[Link]();
}}
Object-oriented Programming
Access Modifier Access within within outside
The access modifiers in Java Modifier class package package
specifies the accessibility or scope Private Y N N
of a field, method, constructor, or
Default Y Y N
class.
 Private Access Modifier Protected Y Y N
The private access modifier is Public Y Y Y
accessible only within the class.

 Default Access Modifier


 If no modifier is mentioned then it is treated as default.
 The default modifier is accessible only within package.
 It cannot be accessed from outside the package.
 It provides more accessibility than private.
 But, it is more restrictive than protected, and public.
Object-oriented Programming
Access Modifier
class A{
private int data=40;
private void msg(){
[Link]("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
} }

Class A contains private data member and private method.


Compile-time error due to accessing these private members from outside
the class.
Object-oriented Programming
Access Modifier
class A{
private int data=40;
private void msg(){
[Link]("Hello java");}
public void printName(){
msg();}
public int getData(){
return data;}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]();
[Link]();
} }
Constructors in Java
Constructors are similar to methods, but they are used to initialize an
object.
Constructors do not have any return type (not even void).
Every time we create an object by using the new() keyword, a constructor is
called.
If we do not create a constructor by ourself, then the default
constructor(created by Java compiler) is called.
Rules for creating a Constructor :
 The class name and constructor name should be the same.
 It must have no explicit return type.
Types of Constructors in Java :
There are two types of constructors in Java :
1. Defaut constructor : A constructor with 0 parameters
2. Paramerterized constructor : A constructor with some specified number
of parameters
Constructors in Java
1. Defaut constructor Syntax
<class_name>(){
//code to be executed on the execution of the constructor
}
Example:
class CWH {
CWH(){
[Link]("This is the default constructor of CWH class.");
}
}
public class CWH_constructors {
public static void main(String[] args) {
CWH obj1 = new CWH();
}}
Constructors in Java
2. Paramerterized Constructor Syntax
<class-name>(<data-type> param1, <data-type> param2,......){
//code to be executed on the invocation of the constructor
}
Example:
class CWH {
CWH(String s, int b){
[Link]("This is the " +b+ "th video of "+ " "+ s);
}}
public class CWH_constructors {
public static void main(String[] args) {
CWH obj1 = new CWH("CodeWithHarry Java Playlist",42);
}}
Constructor Overloading in Java :
 Just like methods, constructors can also be overloaded in Java.
class Employee {
Employee(String s, int i){
[Link]("The name of the first employee is : " + s);
[Link]("The id of the first employee is : " + i);
}
// Constructor overloaded
Employee(String s, int i, int salary){
[Link]("The name of the second employee is : " + s);
[Link]("The id of the second employee is : " + i);
[Link]("The salary of second employee is : " + salary);
}}
public class CWH_constructors {
public static void main(String[] args) {
Employee shubham = new Employee("Shubham",1);
Employee harry = new Employee("Harry",2,70000);
}}

You might also like