You are on page 1of 33

Chapter Four:

Java Objects and Classes

Part Two
1
Types of Method
There are two types of methods in Java:
❖Predefined Method
❖User-defined Method

2
Predefined Method
❖ In Java, predefined methods are the method that is
already defined in the Java class libraries is known as
predefined methods. 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

3
Continue…
Let's see an example of the predefined method.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9

4
Continue…
❖ In the above example, we have used three predefined
methods main(), print(), and max(). We have used
these methods directly without declaration because
they are predefined. The print() method is a method
of PrintStream class that prints the result on the
console. The max() method is a method of
the Math class that returns the greater of two numbers.

5
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.
Types of user defined methods
❖ Static method
❖ Instance method
❖ Abstract method

6
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 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 in other classes.

7
• Static variables – called as class variable
• Static methods – called as class methods
❑static variable:
❑declare any variable as static, it is known static
variable.
❑static method:
❑static keyword with any method, it is known as static
method.
❑A static method belongs to the class rather than object
of a class.
❑invoked without the need for creating an instance of a
class. 8
Example …
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}}
Output: It is an example of static method

9
Instance Method
❖It is a non-static method defined in the class.
Before calling or invoking the instance method, it
is necessary to create an object of its class. Let's see
an example of an instance method.

10
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; } }
output: the sum is: 25
11
Types of instance method
There are two types of instance method:
❖Accessor Method
❖Mutator Method
Accessor Method: The method(s) that reads the
instance variable(s) is known as the accessor method.
We can easily identify the accessor methods because
the method is prefixed with the word get. It is also
known as getters. It returns the value of the private
field/variables. It is used to get the value of the
private field. public int getId()
{
Example: return Id;
12
}
Continue…
Mutator Method: The method(s) read the instance
variable(s) and also modify the values. We can easily
identify mutator mehods because the method is
prefixed with the word set. It is also known
as setters or modifiers.
It does not return anything. It accepts a parameter of
the same data type. It is used to set the value of the
private field/variables.
Example:
public void setRoll(int roll)
{
this.roll = roll;
}
13
Example of accessor and mutator method
public class Student public String getName()
{ {
private int roll; return name;
}
private String name; public void setName(String name)
//accessor method {
public int getRoll() this.name = name;
{ }
return roll; public void display()
{
} System.out.println("Roll no.: "+roll);
//mutator method
public void setRoll(int roll) System.out.println("Student name: "
+name);
{ }
this.roll = roll; }
}
14
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.
❖It means the class itself must be abstract if it has
abstract method. To create an abstract method, we
use the keyword abstract.
❖Syntax
abstract void method_name();

15
❑ Abstract keyword
❑ Abstract class in Java
• class that is declared with abstract keyword, is known
as abstract class
abstract class <class_name>
{
}
❑ abstract method
• method that is declared as abstract - abstract method
• does not have implementation, it’s in derived class
Syntax:
abstract return_type <method_name>();//no braces{}

16
Example of abstract method
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{ Output:
//method impelmentation
void display() Abstract mehod?
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
} }
18
Constructor in Java

• Constructor is a special type of method that is used to


initialize the object.

• Constructor is invoked at the time of object creation.

• Rules for creating constructor


• Constructor name must be same as its class name
• Constructor Name=Class Name

• Constructor must have no explicit return type

19
Types of Constructors
• Default constructor (No-argument constructor)
• A constructor that have no parameter
• Default values to the object like 0, null etc.
depending on the type.
<class_name>()
{
}
• Parameterized constructor
• A constructor that have parameters
• Used to provide different values to the distinct
objects.
<class_name>(parameter list)
{
} 20
Example:
class Student
public static void main(String args[])
{
{
int id;
Student s1 = new Student(111,“Abay");
String name;
Student(int i,String n)
Student s2 = new Student(222,“Gebissa");
{
id = i;
s1.display();
name = n;
s2.display(); } }
}
void display(){
System.out.println(id+" "+name);
}
Output
111Abay
222 Gebissa
21
Constructor Overloading

❖ Constructor overloading is a technique in


Java in which a class can have any number
of constructors that differ in parameter lists.
❖ The compiler differentiates these constructors
by taking into account the number of
parameters in the list and their type.

22
❑Constructor Overloading
class Student void display()
{ {
int id; System.out.println(id+" "+name+" "+age);
String name; }
int age; public static void main(String args[])
Student(int i,String n) {
{ Student s1 = new Student(111,“yemane");
id = i; Student s2 = new
name = n; Student(222,"Aryan",25);
} s1.display();
Student(int i,String n,int a) s2.display();
{ }
id = i; }
name = n;
age=a;
} 23
Parameters and Arguments
Information can be passed to methods as
parameter. Parameters acts as variables inside
the method.
public class Main
{
static void myMethod(String fname)
{
System.out.println(fname + " Refsnes"); }
public static void main(String[] args)
{
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja"); } }
28
Parameter passing
1. Pass By Value: When a parameter is pass-by-value, the
caller and the callee method operate on two different
variables which are copies of each other. Any changes
to one variable don't modify the other. It means that
while calling a method, parameters passed to the
callee method will be clones of original
parameters. Any modification done in callee method
will have no effect on the original parameters in caller
method.

29
Continue….
class CallByValue {
public static void Example(int x, int y)
{
x++;
y++;
}}
public class Main {
public static void main(String[] args)
{
int a = 10, b=20;
// Instance of class is created
CallByValue object = new CallByValue();

30
Continue…

System.out.println("Value of a: " + a + " & b: " + b);

// Passing variables in the class function


object.Example(a, b);

// Displaying values after


// calling the function
System.out.println("Value of a: "+ a + " & b: " + b);
}}
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20
31
Continue…
2. Call by reference(aliasing): When a parameter is pass-
by-reference, the caller and the callee operate on the
same object. Any changes to the parameter’s instance
members will result in that change being made to the
original value.

32
continue…
class CallByReference {
int a, b;
// Function to assign the value
// to the class variables
CallByReference(int x, int y) {
a = x;
b = y; }
// Changing the values of class variables
void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20; }}
// Caller
public class Main {
public static void main(String[] args) {
// Instance of class is created
// and value is assigned using constructor 33
CallByReference object = new CallByReference(10, 20);
continue…
System.out.println("Value of a: "+ object.a + " & b: “ + object.b);
// Changing values in class function
object.ChangeValue(object);
// Displaying values
// after calling the function
System.out.println("Value of a: "+ object.a + " & b:+ object.b); }}

Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
34
Encapsulation
• Encapsulation is one of the four fundamental OOP
concepts.
• The other three are inheritance, polymorphism, and
abstraction.
• Encapsulation in Java is a mechanism of wrapping the
data (variables) and code acting on the data (methods)
together as a single unit.
• In encapsulation, the variables of a class will be hidden
from other classes, and can be accessed only through the
methods of their current class. Therefore, it is also known
as data hiding.
• To achieve encapsulation in Java −
– Declare the variables of a class as private.
– Provide public setter and getter methods to modify and view the
variables values.

35
Example
public class EncapTest {
private String name;
private String idNum;
private int age;
public int getAge() {
return age; }
public String getName() {
return name; }
public String getIdNum() {
return idNum; }
public void setAge( int newAge) {
age = newAge; }
public void setName(String newName) {
name = newName; }
public void setIdNum( String newId) {
idNum = newId;
}} 36
Con’t
• The public setXXX() and getXXX() methods are the access points
of the instance variables of the EncapTest class.
• Normally, these methods are referred as getters and setters.
Therefore, any class that wants to access the variables should
access them through these getters and setters.
• The variables of the EncapTest class can be accessed using the
following program:
public class RunEncap {
public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " +
encap.getAge()); } }

37
Thank You

?
38

You might also like