SlideShare a Scribd company logo
Blue Ridge Junior College
Class XI – Computer Science
Ch 7 & 8 – Classes in Java and Functions
1
Blue
Ridge
Junior
College
Topics
• Encapsulation
• Access Specifiers
• Scope and Visibility Rules
• What are Functions?
• Defining Functions
• Classification of Functions
• Calling and Accessing Functions
• Function Overloading
• Objects as Parameters
• Constructors
2
Blue
Ridge
Junior
College
Encapsulation
• Encapsulation is one of the four fundamental OOP concepts
• 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
3
Blue
Ridge
Junior
College
Access Specifiers
• The access to classes, constructors, methods and fields are
regulated using access modifiers
• A class can control what information or data can be accessible
by other classes
• Java provides a number of access modifiers to help you set the
level of access you want for classes as well as the fields,
methods and constructors in your classes
4
Blue
Ridge
Junior
College
Access Specifiers – cont.
• In Java, methods and data members of a class/interface can
have one of the following four access specifiers
• Visible to the package, the default. No modifiers are needed.
• Visible to the class only (private)
• Visible to the world (public)
• Visible to the package and all subclasses (protected)
5
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Default Access Modifier - No Keyword
• If you do not use any modifier, it is treated as default
• Default access modifier means we do not explicitly declare an
access modifier for a class, field, method, etc.
• A variable or method declared without any access control
modifier is available to any other class in the same package
• The default modifier is accessible only within package
6
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Default Access Modifier - No Keyword
• Example of default access modifier
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
• In this example, we have created two packages pack and mypack.
We are accessing the A class from outside its package, since A class
is not public, so it cannot be accessed from outside the package
7
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Private Access Modifier - Private
• Methods, variables, and constructors that are declared private
can only be accessed within the declared class itself
• Private access modifier is the most restrictive access level
• Using the private modifier is the main way that an object
encapsulates itself and hides data from the outside world
• Classes and interfaces cannot be private
8
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Private Access Modifier - Private
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
• In this example, we have created two classes A and
Simple
• A class contains private data member and private
method
• We are accessing these private members from
outside the class, so there is compile time error
9
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Public Access Modifier - Public
• A class, method, constructor, interface, etc. declared public can
be accessed from any other class
• Therefore, fields, methods, blocks declared inside a public class
can be accessed from any class
• However, if the public class we are trying to access is in a
different package, then the public class still needs to be imported
• Because of class inheritance, all public methods and variables of a
class are inherited by its subclasses
10
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Public Access Modifier - Public
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
• Output:Hello
11
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Protected Access Modifier - Protected
• Variables, methods, and constructors, which are declared
protected in a superclass can be accessed only by the subclasses
in other package or any class within the package of the protected
members' class
• The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however
methods and fields in a interface cannot be declared protected
12
Blue
Ridge
Junior
College
Access Specifiers – cont.
• Protected Access Modifier - Protected
//save by A.java
package pack;
public class A
{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
• Output: Hello
• In this example, we have created the two packages pack and mypack
• The A class of pack package is public, so can be accessed from outside the package
• But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance
13
Blue
Ridge
Junior
College
Access Specifiers – cont.
• The following rules for inherited methods (for overriding) are
enforced:
• Methods declared public in a superclass also must be public in all
subclasses
• Methods declared protected in a superclass must either be
protected or public in subclasses; they cannot be private
• Methods declared private are not inherited at all, so there is no
rule for them
14
Blue
Ridge
Junior
College
Scope and Visibility Rules
• The scope of a variable defines the section of the code in
which the variable is visible
• Variable scope refers to the accessibility of a variable
• The lifetime of a variable refers to how long the variable exists
before it is destroyed
• As a general rule, variables that are defined within a block are
not accessible outside that block
15
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• The scope rules of a language are the rules that decide in
which part of the program a particular piece of code or data
item would be known and can be accessed
• The program part in which a particular piece of code or a data
value (e.g., variable) can be accessed is known as the
variable's Scope
• There are three types of variables:
• instance variables
• class variables
• local variables
16
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Instance Variables
• Instance variables are those that are defined within a class itself
and not in any method or constructor of the class
• They are known as instance variables because every instance of
the class (object) contains a copy of these variables
• Instance variables are created when an object is created with
the use of the keyword 'new' and destroyed when the object is
destroyed
• The scope of instance variables is determined by the access
specifier that is applied to these variables
• The lifetime of these variables is the same as the lifetime of the
object to which it belongs
17
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Instance Variables
public class Record{
public String name;// this instance variable is visible for any child class.
private int age;// this instance age variable is visible in Record class only.
public Record (String RecName)
{
name = RecName;
}
public void setAge(int RecSal)
{
age = RecSal;
}
public void printRec()
{
System.out.println("name : " + name ); // print the value for “name”
System.out.println("age :" + age); //prints the value for “age”
}
public static void main(String args[])
{
Record r = new Record("Ram");
r.setAge(23);
r.printRec();
}
}
• Output
name : Ram
age :23
18
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Class Variables
• Class variables are those that are defined within a class itself
and not in any method or constructor of the class using the
keyword static
• Difference between non static instance variable and a static
class variable is that an instance variable is a separate copy and
the class variable is the same copy for all objects of the class
• Object not needed to reference a class variable
19
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Local Variables
• A local variable is the one that is declared within a method or a
constructor (not in the header)
• The scope and lifetime are limited to the method itself
• In addition to the local variables defined in a method, we also
have variables that are defined in blocks like an if block and an
else block
• The scope and life is the same as that of the block itself
20
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Local Variables
public class Dog
{
public void putAge()
{
int age = 0; //local variable
age = age + 6;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]){
Dog d = new Dog();
d.putAge();
}
}
• Here, age is a local variable
• This variable is defined under putAge() method and its scope is
limited to this method only
21
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Local Variables
• In Java, we can create nested blocks – a block inside another block.
• All the local variables in the outer block are accessible within the inner block but
vice versa is not true i.e., local variables within the inner block are not accessible
in the outer block
public static void main(String[] args)
{
int x;
//Begining of inner block
{
int y = 100;
x = 200;
System.out.println("x = "+x);
}
//End of inner block
System.out.println("x = "+x);
y = 200; //Error as y is not accessible in the outer block
}
}
• As you can see in the above program, an error is generated as the
variable ”y” is not visible in the outer block and therefore cannot be accessed
22
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Formal Parameters or Argument variables
• These are the variables that are defined in the header of
constructor or a method
• The scope of these variables is the method or constructor in
which they are defined
• The lifetime of these variables is limited to the time for which the
method keeps executing
• Once the method finishes execution, these variables are
destroyed
23
Blue
Ridge
Junior
College
Scope and Visibility Rules – cont.
• Formal Parameters or Argument variables
public class Test
{
private int num;
public void method(int x)
{
num=x;
}
public static void main(String args[])
{
Test t = new Test();
t.method(5);
}
}
24
Blue
Ridge
Junior
College
What are Functions?
• A Java method or a function is a collection of statements that
are grouped together to perform an operation
• Technically, a function is a subprogram within a main program,
which processes data and returns a value
• Each function has a unique name with which it is called within
a program
• A method or function can be called (invoked) at any point in a
program simply by utilizing the method's / function’s name 25
Blue
Ridge
Junior
College
What are Functions? – cont.
• As stated earlier, each method has its own name. When that
name is encountered in a program, the execution of the
program branches to the body of that method
• When the method is completed, execution returns to the area
of the program code from which it was called, and the
program continues on to the next line of code
26
Blue
Ridge
Junior
College
Need for Functions
• When you start writing real programs, you
would realize that they can grow to many pages
of code
• A full-length program contains many pages of
code, and trying to find a specific part of the
program in all that code can be tough
• When programs get long, they also get harder
to organize and read
• To overcome this problem, professional
programmers break their programs down into
individual functions, each of which completes a
specific and well-defined task
27
Blue
Ridge
Junior
College
Need for Functions – cont.
• Using modular programming techniques, you can
break a long program into individual modules, each
of which performs a specific task
• When you break your program's modules down into
even smaller modules, you are using a top-down
approach to program design
• By using top-down programming techniques, you
can write any program as a series of small, easy-to-
handle tasks
• In Java, the basic unit for organizing code in a top-
down manner is the function
28
Blue
Ridge
Junior
College
Need for Functions – cont.
• Functions are time savers, in that they allow for the repetition
of sections of code without retyping the code
• In addition, functions can be saved and utilized again and
again in newly developed programs
• The use of methods will be our first step in the direction of
modular programming
29
Blue
Ridge
Junior
College
Defining Functions
• The general format of defining function in a java
class is as follows:
• [access specifier][static][return type] function-
name (formal parameters)
• access specifier: It defines the access type of the method. This
can be public, private, protected or default. By default, functions
have public access specifier
• static: The static keyword enables the function to be called
without creating an object
• return-type: The data type of the value returned by the method,
or void if the method does not return a value
30
Blue
Ridge
Junior
College
Defining Functions – cont.
• function-name: This is the name of the function
• formal parameters: The list of parameters - it is the type, order,
and number of parameters of a method. These are optional,
method may contain zero parameters. If there are no parameters,
you must use empty parentheses
• function body: The set of statements that would get executed
when the function is called.
31
Blue
Ridge
Junior
College
Defining Functions – cont.
• function-header: This is the first line which contains the access
specifier, return type, function name and list of parameters.
• formal signature: A method signature is written by using the
method name along with the parameters to be passed to the
method. Example of method signature: test(int a, int b)
32
Blue
Ridge
Junior
College
Defining Functions – cont.
• Naming a Method / Function
• Although a method name can be any legal identifier,
code conventions restrict method names
• By convention, method names should be a verb in
lowercase or a multi-word name that begins with a
verb in lowercase, followed by adjectives, nouns, etc.
• In multi-word names, the first letter of each of the
second and following words should be capitalized.
Here are some examples:
• run
• runFast
• getBackground
• getFinalData
33
Blue
Ridge
Junior
College
Defining Functions – cont.
• A method's declaration provides a lot of information about
the method to the compiler, the runtime system and to other
classes and objects
• Besides the name of the method, the method declaration
carries information such as the return type of the method, the
number and type of the arguments required by the method,
and what other classes and objects can call the method
34
Blue
Ridge
Junior
College
Classification of Functions
• A Java program is basically a set of classes
• A class is defined by a set of declaration statements
and methods or functions
• Java programming supports different types of
function as in User Defined Function (UDF)(A
function which is created by user so it is known as
user defined function) and also there are some
functions available within the Java packages that
provide some imperative support to the java
programmer for developing their programming logic
as well as their programming architecture
35
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Predefined Functions
• The Java API or application programming interface is a collection
of software packages that programmers can use for graphics, user
interface, networking, sound, database, math, and much more
• It contains many methods that have already been written and
tested
• In order to use these specific methods in our program we have to
import the necessary libraries by adding them to our program
36
Blue
Ridge
Junior
College
Classification of Functions – cont.
• User Defined Functions
• Functions defined by the programmer within the program to use
it for a particular task
• User defined function is totally based on the user control
• When we create user define function name then we must
remember some special point that points are given below
• We cannot use any reserved keywords
• We can use the same function name for the different
numbers of types of arguments list
• So, we can overload our user-defined functions in our system
• The function name can only comprehend letters, numbers,
and the underscore (_)
• Function name must start with a letter
• The function names which cannot be exceed 128 characters
37
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Functions are mostly used to produce some computational
output
• Actions inside a function may be like reading and displaying
some data values; assigning or modifying some existing
values; computing and returning a result for further use, etc.
• Out of all such actions, some operations like write or modify
can disturb or change the value of some already stored
member-data. Therefore, write or update operations are to
be treated very carefully and unrestricted public access
should not be allowed
• On the other hand, read or display operations are not
destructive, because read operations do not change data
values. So no access restriction will be necessary for such
operations
• Based on the operational side effects, functions can be
classified as either pure functions or impure functions
38
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Pure Functions
• A pure function, when invoked, does not cause any change in the
state of an object, that means there will be no change in the
values of the object’s instance variables
• For example readData() or getData() functions can be treated as
pure functions as they do not change any existing data values
• Pure functions can safely be declared as public also
39
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Pure Functions
• Code snippet for pure function:
class add
{
void sum(int a, int b)
{
int c = calc(a,b);
System.out.println(“The sum is” +c);
}
int calc(int a, int b)
{
int c=a+b;
return(c);
}
}
When a method contains a return statement, it is always the final
statement of that method, because no further statements in the
method will be executed once the return statement is executed
40
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Impure Functions
• Impure functions, also called modifier functions, are those that
can cause a change of state in the object
• Values of the object’s instance variables get modified or changed
depending on the current state of the object on which the
function operates
• Such functions can cause some unwanted side effects if not
carefully controlled by the access-modifier
41
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Impure Functions
• Demonstration of an Impure Function
public class ImpureFncTest
{
String name;
int accNo;
double accBalance;
double withdrawVal;
public double transaction(double balance, double withdraw)
{
if
( withdraw > balance) {System.out.println("Sorry !! Transaction Impossible.");}
else
{balance = balance - withdraw;System.out.println("Transaction Successful.");}
return balance
;}
public void show( double bal){
System.out.println ( "Balance Available : " + bal);}
public static void main()
{// manipulation of the first object
ImpureFncTest customer1 = new ImpureFncTest();//first object
customer1.name = " Anita Kar";
customer1.accNo = 8912;
customer1.accBalance = 123456.50;
customer1.withdrawVal = 5000.00;
System.out.println ( customer1.name + " -- Account No. :: " + customer1.accNo);customer1.accBalance =
customer1.transaction(customer1.accBalance,customer1.withdrawVal);customer1.
show(customer1.accBalance);
// manipulation of the second object
ImpureFncTest customer9 = new ImpureFncTest();//second object
customer9.name = " Kalyan Bhatt";
customer9.accNo = 13245;
customer9.accBalance = 3592.75;
customer9.withdrawVal = 4000.00;
System.out.println ( customer9.name + " -- Account No. :: " + customer9.accNo);customer9.accBalance =
customer9.transaction(customer9.accBalance,customer9.withdrawVal);customer9.
show(customer9.accBalance);
} }
42
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Impure Functions
• In this example, transaction (double, double) is an impure
function, because it causes a change in the object’s state by
changing the value of the Balance Available
43
Blue
Ridge
Junior
College
Classification of Functions– cont.
• Function can also be classified as follows depending upon the
function definition:
• Function which does not have argument or a return type
• Function which has an argument but no return type
• Function which has no argument but has a return type
• Function which has both an argument and return type
44
Blue
Ridge
Junior
College
Classification of Functions – cont.
• To understand this concept, we need to first cover returning
values from a function
• A method returns to the code that invoked it when it
• completes all the statements in the method,
• reaches a return statement, or
• throws an exception (covered later),
whichever occurs first
You declare a method's return type in its method declaration.
Within the body of the method, you use the return statement
to return the value.
45
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Any method declared void doesn't return a value. It does not
need to contain a return statement, but it may do so
• In such a case, a return statement can be used to branch out
of a control flow block and exit the method and is simply
used like this:
• return;
• If you try to return a value from a method that is
declared void, you will get a compiler error.
• Any method that is not declared void must contain
a return statement with a corresponding return value, like
this:
• return returnValue;
• The data type of the return value must match the method's
declared return type; you can't return an integer value from a
method declared to return a boolean
46
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Function which does not have argument or a return type
• Such functions do not have any argument and the return type is
void as the function only performs activities like computation
and printing
class ABC
{
void add()
{
int a=10;
int b=20;
int c=a+b;
System.out.println(c);
}
}
The void keyword allows us to create methods which do not return a value 47
Blue
Ridge
Junior
College
Classification of Functions – cont.
• Function which has an argument but no return type
• Such functions may have single or multiple arguments and
return nothing
class ABC
{
void add(int a, int b)
{
int c=a+b;
System.out.println(c);
}
}
• When passing arguments or parameters to a method, it should
be in the same order as their respective parameters in the
method specification
48
Blue
Ridge
Junior
College
Classification of Functions – cont.
 Function which has no argument but has a return type
 Such functions do not have any argument but return a value
using the return keyword
class ABC
{
int add()
{
int a=10;
int b=20;
int c=a+b;
return c;
}
} 49
Blue
Ridge
Junior
College
Classification of Functions – cont.
 Function which has both an argument and return type
class ABC
{
int add(int a, int b)
{
int c=a+b;
return c;
}
}
50
Blue
Ridge
Junior
College
Calling and Accessing Functions
• Methods don't do anything until you call them into action
• The process of method calling is simple. When a program
invokes a method, the program control gets transferred to the
called method
• This called method then returns control to the caller in two
conditions, when −
• the return statement is executed.
• it reaches the method ending closing brace
51
Blue
Ridge
Junior
College
Calling and Accessing Functions
• The main() function gets executed first and then the other
functions are called
• All functions contained within the main() function are called
sub-functions
• A function can be called in two ways depending upon the
main() function
• Functions that are within the same class as the main()
method:
• In this case, the function can be directly called by the main()
method without needing an object to do so
52
Blue
Ridge
Junior
College
Calling and Accessing Functions
• Example:
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
53
Blue
Ridge
Junior
College
Calling and Accessing Functions
• Functions that are in a different class from the class with the main() method
• In this case, the function can be called by the main() method in two ways:
• If the method is static, it can be called using the classname and the dot operator
class Student
{
int rollno;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
public static void main(String args[])
{
change(); //main of the same class
}
} //end of class Student
class Test
{
public static void main(String args[])
{
Student.change(); //calling function of another class
}
}
54
Blue
Ridge
Junior
College
Calling and Accessing Functions
• If the method is non static, then we create an object and call the method using the dot operator
on the object
class Student1{
int rollno;
String name;
String college = "ITS";
Student1(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}// end of class Student1
class Test1
{
int a=5;
public static void main(String args[])
{
Student1 s = new Student1 (111,"Karan"); //creating object for Student1 class
s.display(); //calling method of another class
}
}
55
Blue
Ridge
Junior
College
Function Overloading
• Function Overloading is a feature that allows a class to have
two or more methods having same name, if their argument
lists are different
• Overloading always occurs in the same class
• Method overloading is one of the ways through which Java
supports polymorphism
• Method overloading can be done by changing number of
arguments or by changing the data type of arguments
• If two or more methods have the same name and same
parameter list but differ in return type, they are not said to
be overloaded method
56
Blue
Ridge
Junior
College
Function Overloading – cont.
• When an overloaded method is invoked, Java uses the type
and/or number of arguments as its guide to determine which
version of the overloaded method to actually call
• Thus, overloaded methods must differ in the type and/or
number of their parameters
• When Java encounters a call to an overloaded method, it
simply executes the version of the method whose parameters
match the arguments used in the call
57
Blue
Ridge
Junior
College
Function Overloading – cont.
• Need for Function Overloading
• Using the concept of function overloading, a family of functions
can be designed , with one function name but different
parameter lists
• This is how java supports polymorphism using function
overloading, "one interface, multiple methods paradigm‘
• One benefit of overloading is that you can access related
methods by using common name
• Function overloading avoids coding error if there are different
methods names and a wrong method is coded by the
programmer
58
Blue
Ridge
Junior
College
Function Overloading – cont.
• 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 TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
• In this example, we have created two methods, first add()
method performs addition of two numbers and second add()
method performs addition of three numbers
• In this example, we have creating static methods so that we
don't need to create instance for calling methods
59
Blue
Ridge
Junior
College
Function Overloading – cont.
• Changing data type of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
• In this example, we have created two methods that differs in data
type
• The first add method receives two integer arguments and second
add method receives two double arguments
60
Blue
Ridge
Junior
College
Recursive Function
• A function designed in such a way that it calls itself in its body
is called Recursive Function
61
Blue
Ridge
Junior
College
Objects as Parameters
• We can pass object of any class as parameter to a
method in Java
• For example, consider the following program:
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
Output of the program :
Area of Rectangle : 200
62
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• We can access the instance variables of the object passed
inside the called method
• Like area = r1.length * r1.width
• It is a good practice to initialize instance variables of an object
before passing object as parameter to the method. Otherwise
it will take the default initial values
63
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• Call by Value and Call by Reference
• Before we look into what the terms call by value and call by reference mean, let
us look at two simple programs and examine their output:
class CallByValue {
public static void main ( String[] args ) {
int x =3;
System.out.println ( "Value of x before calling increment() is "+x);
increment(x);
System.out.println ( "Value of x after calling increment() is "+x);
}
public static void increment ( int a ) {
System.out.println ( "Value of a before incrementing is "+a);
a= a+1;
System.out.println ( "Value of a after incrementing is "+a);
}
}
The output of this program would be:
Value of x before calling increment() is 3
Value of a before incrementing is 3
Value of a after incrementing is 4
Value of x after calling increment() is 3
64
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• As is evident from the output, the value of x has remain unchanged, even though it
was passed as a parameter to the increment() method
• And now, we move on to the second program, where we will make use of class
Number that contains a single instance variable x
class Number {
int x;
}
class CallByReference {
public static void main ( String[] args ) {
Number a = new Number();
a.x=3;
System.out.println("Value of a.x before calling increment() is "+a.x);
increment(a);
System.out.println("Value of a.x after calling increment() is "+a.x);
}
public static void increment(Number n) {
System.out.println("Value of n.x before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of n.x after incrementing x is "+n.x);
}
}
This program would give the following output
Value of a.x before calling increment() is 3
Value of n.x before incrementing x is 3
Value of n.x after incrementing x is 4
Value of a.x after calling increment() is 4
65
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• In the first program, the change made to the variable a inside
the increment() method had no effect on the original variable
x that was passed as an argument
• On the other hand, in the second program, changes made to
the variable x that was a part of the object in the increment()
method had an effect on the original variable ( the object
which contained that integer variable) that was passed as an
argument
• The difference lies in the type of the variable that was passed
as an argument
• int is a primitive data type while Number is a reference data
type
• Primitive data types in Java are passed by value while
reference data types are passed by reference
66
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• What we mean by passing a variable by value is that the
value held in the variable that is passed as an argument
is copied into the parameters that are defined in the
method header
• That is why changes made to the variable within the
method had no effect on the variable that was passed
• On the other hand, when objects are passed, the object
itself is passed
• No copy is made. Therefore changes made to the object
within the method increment() had an effect on the
original object
67
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• The following figure illustrate call be reference and call by
value
68
Blue
Ridge
Junior
College
Objects as Parameters – cont.
• The concept of call by reference can be better understood if
one tries to look into what a reference actually is and how a
variable of a class type is represented
• When we declare a reference type variable, the compiler
allocates only space where the memory address of the object
can be stored. The space for the object itself isn't allocated
• The space for the object is allocated at the time of object
creation using the new keyword
• A variable of reference type differs from a variable of a
primitive type in the way that a primitive type variable holds
the actual data while a reference type variable holds the
address of the object which it refers to and not the actual
object. 69
Blue
Ridge
Junior
College
Static Members and Functions
• static is a Java keyword. It can be applied to a field, a method
or an inner class
• If you declare any variable as static, it is known as a static
variable
• The static keyword in Java means that the variable or
function is shared between all instances of that class as it
belongs to the type, not the actual objects themselves
• The static variable gets memory only once in class area at the
time of class loading
• So if you have a variable: private static int i = 0; and you
increment it (i++) in one instance, the change will be
reflected in all instances. i will now be 1 in all instances 70
Blue
Ridge
Junior
College
Static Members and Functions –
cont.
• Java static variable
• It is a variable which belongs to the class and not to object(instance)
• Static variables are initialized only once, at the start of the execution.
These variables will be initialized first, before the initialization of any
instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<variable-name>
71
Blue
Ridge
Junior
College
Static Members and Functions –
cont.
• Java Static Functions
• It is a method which belongs to the class and not to
the object(instance)
• A static method can access only static data. It can not access non-
static data (instance variables)
• A static method can call only other static methods and can not
call a non-static method from it.
• A static method can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<method-name>
72
Blue
Ridge
Junior
College
Static Members and Functions –
cont.
• Understanding problem without static variables
class Student{
int rollno;
String name;
String college="ITS";
}
• Suppose there are 500 students in my college, now all
instance data members will get memory each time when
object is created
• All student have its unique rollno and name so instance data
member is good
• Here, college refers to the common property of all objects
• If we make it static, this field will get memory only once.
73
Blue
Ridge
Junior
College
Static Members and Functions –
cont.
class Student{
int rollno;
String name;
static String college ="IIT";
Student(int r,String n){
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student s1 = new Student(111,“Raj");
Student s2 = new Student(222,“Shubham");
s1.display();
s2.display();
}
}
Output:
111 Raj IIT
222 Shubham IIT
74
Blue
Ridge
Junior
College
Static Members and Functions –
cont.
• Difference between Static variables and Instance variables:
• Static variables and instance variables both are member
variables because they are both associated with a specific class,
but the difference between them is Static variables has only one
copy that is shared by all the different objects of a class,
whereas every object has its own personal copy of an instance
variable
• So, instance variables across different objects can have different
values whereas static variables across different objects can have
only one value
• Both are declared at class level outside any method
• Static variables are also called class variables
75
Blue
Ridge
Junior
College
What are Constructors?
• A constructor in Java is a block of code similar to a method
that is called when an instance of an object is created
• It is a special method that is used to initialize a newly created
object
• Java constructor is invoked at the time of object creation
• It constructs the values i.e. provides data for the object that is
why it is known as constructor
76
Blue
Ridge
Junior
College
What are Constructors – cont.
• Key differences between a constructor and a method
• A constructor doesn’t have a return type (not even void) since
the basic aim is to place the value in the object. If we write the
return type for the constructor then that constructor will be
treated as ordinary method
• The name of the constructor must be the same as the name of
the class
• Constructor definitions should not be static as constructors will
be called each and every time, whenever an object is created
77
Blue
Ridge
Junior
College
What are Constructors – cont.
• Unlike methods, constructors are not considered members of a
class
• A constructor is called automatically when a new instance of an
object is created
78
Method Constructor
Method can be any user
defined name
Constructor must be class
name
Method should have return
type
It should not have any return
type (even void)
Method should be called
explicitly either with object
reference or class reference
It will be called automatically
whenever object is created
Method is not provided by
compiler in any case
The java compiler provides a
default constructor if we do
not have any constructor
Blue
Ridge
Junior
College
Need for Constructors
• It can be cumbersome to initialize all variables in a call each
time an instance of a class in created
• Constructors are mainly created for initializing the object
• Initialization is a process of assigning user defined values at
the time of allocation of memory space
• An advantage of constructors in Java is it eliminates placing
the default values
79
Blue
Ridge
Junior
College
Need for Constructors – cont.
• Whenever we create an object of any class, memory is
allocated memory for all the data members and their
values are initialized to their default values
• To eliminate these default values by user defined values
we use constructor
80
Blue
Ridge
Junior
College
Constructor Example
class Programming
{ //constructor method
Programming()
{
System.out.println("Constructor method called.");
}
public static void main(String[] args)
{
Programming object = new Programming(); //creating object
}
}
81
Blue
Ridge
Junior
College
Types of Constructors
• Based on creating objects in Java, constructor are classified in
two types. They are:
• Default or no argument Constructor
• Parameterized Constructor
82
Blue
Ridge
Junior
College
Types of Constructors – cont.
 Default or no argument Constructor
• A constructor that has no parameter is known as default
constructor
• If we do not define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class
• If we write a constructor with arguments or no-argument then
compiler does not create default constructor
Default constructor provides the default values to the object like
0, null etc. depending on the type
83
Blue
Ridge
Junior
College
Types of Constructors – cont.
• Example of default constructor
• In this example, we are creating the no-argument constructor in
the Bike class
• It will be invoked at the time of object creation
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike ();
}
}
84
Blue
Ridge
Junior
College
Types of Constructors – cont.
• If there is no constructor in a class, compiler automatically
creates a default constructor
• The default constructor is a constructor that the Java
compiler adds to your code if no explicit constructor is
available
• If you have added your own constructor (no matter whether
it's without parameters or with parameters) the compiler will
not add the default constructor in this case
85
Blue
Ridge
Junior
College
Types of Constructors – cont.
• Parameterized Constructor
• A constructor that has parameters is known as parameterized
constructor
• If we want to initialize fields of the class with your own values,
then use parameterized constructor
• This type of constructor accepts parameters and initializes the
data members based on the arguments passed to it
• A parameter is a variable in a method definition. When a method is
called, the arguments are the data you pass into the method's
parameters
public void MyMethod(String myParam) { }
...
String myArg1 = "this is my argument"; myClass.MyMethod(myArg1);
86
Blue
Ridge
Junior
College
Types of Constructors – cont.
• Example of parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
• In this example, we have created the constructor of Student class that has two parameters
• We can have any number of parameters in the constructor
87
Blue
Ridge
Junior
College
Constructor Overloading
• Constructor overloading is a technique in Java in which a class
can have any number of constructors that differ in parameter
lists
• Like methods, we can overload constructors for creating
objects in different ways
• Compiler differentiates constructors on the basis of numbers
of parameters, types of the parameters and order of the
parameters
88
Blue
Ridge
Junior
College
Constructor Overloading – cont.
• Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
89
Blue
Ridge
Junior
College
Constructor Overloading – cont.
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
90
Output
Blue
Ridge
Junior
College
Thank You!!
91
Blue
Ridge
Public
School

More Related Content

Similar to Chapter 7 & 8 Classes in Java and Functions.pdf

Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
MD SALEEM QAISAR
 
4th_class.pdf
4th_class.pdf4th_class.pdf
4th_class.pdf
RumiHossain5
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
Arslan Waseem
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - Encapsulation
Michael Heron
 
Classes in Java great learning.pdf
Classes in Java great learning.pdfClasses in Java great learning.pdf
Classes in Java great learning.pdf
SHASHIKANT346021
 
Inheritance concepts
Inheritance concepts Inheritance concepts
Inheritance concepts
Kumar
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
HarshithaAllu
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdf
ssusere9cd04
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
Ferdin Joe John Joseph PhD
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Chap02
Chap02Chap02
Chap02
Jotham Gadot
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Abdii Rashid
 
C++Presentation 2.PPT
C++Presentation 2.PPTC++Presentation 2.PPT
C++Presentation 2.PPT
VENARATEKANHURU
 
Class Members Access/Visibility Guide (Checklist)
Class Members Access/Visibility Guide (Checklist)Class Members Access/Visibility Guide (Checklist)
Class Members Access/Visibility Guide (Checklist)
Jayasree Perilakkalam
 
Lecture 5 inheritance
Lecture 5 inheritanceLecture 5 inheritance
Lecture 5 inheritance
the_wumberlog
 

Similar to Chapter 7 & 8 Classes in Java and Functions.pdf (20)

Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
4th_class.pdf
4th_class.pdf4th_class.pdf
4th_class.pdf
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - Encapsulation
 
Classes in Java great learning.pdf
Classes in Java great learning.pdfClasses in Java great learning.pdf
Classes in Java great learning.pdf
 
Inheritance concepts
Inheritance concepts Inheritance concepts
Inheritance concepts
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdf
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Chap02
Chap02Chap02
Chap02
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
C++Presentation 2.PPT
C++Presentation 2.PPTC++Presentation 2.PPT
C++Presentation 2.PPT
 
Class Members Access/Visibility Guide (Checklist)
Class Members Access/Visibility Guide (Checklist)Class Members Access/Visibility Guide (Checklist)
Class Members Access/Visibility Guide (Checklist)
 
Lecture 5 inheritance
Lecture 5 inheritanceLecture 5 inheritance
Lecture 5 inheritance
 

Recently uploaded

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 

Recently uploaded (20)

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 

Chapter 7 & 8 Classes in Java and Functions.pdf

  • 1. Blue Ridge Junior College Class XI – Computer Science Ch 7 & 8 – Classes in Java and Functions 1 Blue Ridge Junior College
  • 2. Topics • Encapsulation • Access Specifiers • Scope and Visibility Rules • What are Functions? • Defining Functions • Classification of Functions • Calling and Accessing Functions • Function Overloading • Objects as Parameters • Constructors 2 Blue Ridge Junior College
  • 3. Encapsulation • Encapsulation is one of the four fundamental OOP concepts • 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 3 Blue Ridge Junior College
  • 4. Access Specifiers • The access to classes, constructors, methods and fields are regulated using access modifiers • A class can control what information or data can be accessible by other classes • Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes 4 Blue Ridge Junior College
  • 5. Access Specifiers – cont. • In Java, methods and data members of a class/interface can have one of the following four access specifiers • Visible to the package, the default. No modifiers are needed. • Visible to the class only (private) • Visible to the world (public) • Visible to the package and all subclasses (protected) 5 Blue Ridge Junior College
  • 6. Access Specifiers – cont. • Default Access Modifier - No Keyword • If you do not use any modifier, it is treated as default • Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. • A variable or method declared without any access control modifier is available to any other class in the same package • The default modifier is accessible only within package 6 Blue Ridge Junior College
  • 7. Access Specifiers – cont. • Default Access Modifier - No Keyword • Example of default access modifier //save by A.java package pack; class A{ void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } } • In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package 7 Blue Ridge Junior College
  • 8. Access Specifiers – cont. • Private Access Modifier - Private • Methods, variables, and constructors that are declared private can only be accessed within the declared class itself • Private access modifier is the most restrictive access level • Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world • Classes and interfaces cannot be private 8 Blue Ridge Junior College
  • 9. Access Specifiers – cont. • Private Access Modifier - Private class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } } • In this example, we have created two classes A and Simple • A class contains private data member and private method • We are accessing these private members from outside the class, so there is compile time error 9 Blue Ridge Junior College
  • 10. Access Specifiers – cont. • Public Access Modifier - Public • A class, method, constructor, interface, etc. declared public can be accessed from any other class • Therefore, fields, methods, blocks declared inside a public class can be accessed from any class • However, if the public class we are trying to access is in a different package, then the public class still needs to be imported • Because of class inheritance, all public methods and variables of a class are inherited by its subclasses 10 Blue Ridge Junior College
  • 11. Access Specifiers – cont. • Public Access Modifier - Public //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } • Output:Hello 11 Blue Ridge Junior College
  • 12. Access Specifiers – cont. • Protected Access Modifier - Protected • Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class • The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected 12 Blue Ridge Junior College
  • 13. Access Specifiers – cont. • Protected Access Modifier - Protected //save by A.java package pack; public class A { protected void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B extends A { public static void main(String args[]){ B obj = new B(); obj.msg(); } } • Output: Hello • In this example, we have created the two packages pack and mypack • The A class of pack package is public, so can be accessed from outside the package • But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance 13 Blue Ridge Junior College
  • 14. Access Specifiers – cont. • The following rules for inherited methods (for overriding) are enforced: • Methods declared public in a superclass also must be public in all subclasses • Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private • Methods declared private are not inherited at all, so there is no rule for them 14 Blue Ridge Junior College
  • 15. Scope and Visibility Rules • The scope of a variable defines the section of the code in which the variable is visible • Variable scope refers to the accessibility of a variable • The lifetime of a variable refers to how long the variable exists before it is destroyed • As a general rule, variables that are defined within a block are not accessible outside that block 15 Blue Ridge Junior College
  • 16. Scope and Visibility Rules – cont. • The scope rules of a language are the rules that decide in which part of the program a particular piece of code or data item would be known and can be accessed • The program part in which a particular piece of code or a data value (e.g., variable) can be accessed is known as the variable's Scope • There are three types of variables: • instance variables • class variables • local variables 16 Blue Ridge Junior College
  • 17. Scope and Visibility Rules – cont. • Instance Variables • Instance variables are those that are defined within a class itself and not in any method or constructor of the class • They are known as instance variables because every instance of the class (object) contains a copy of these variables • Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed • The scope of instance variables is determined by the access specifier that is applied to these variables • The lifetime of these variables is the same as the lifetime of the object to which it belongs 17 Blue Ridge Junior College
  • 18. Scope and Visibility Rules – cont. • Instance Variables public class Record{ public String name;// this instance variable is visible for any child class. private int age;// this instance age variable is visible in Record class only. public Record (String RecName) { name = RecName; } public void setAge(int RecSal) { age = RecSal; } public void printRec() { System.out.println("name : " + name ); // print the value for “name” System.out.println("age :" + age); //prints the value for “age” } public static void main(String args[]) { Record r = new Record("Ram"); r.setAge(23); r.printRec(); } } • Output name : Ram age :23 18 Blue Ridge Junior College
  • 19. Scope and Visibility Rules – cont. • Class Variables • Class variables are those that are defined within a class itself and not in any method or constructor of the class using the keyword static • Difference between non static instance variable and a static class variable is that an instance variable is a separate copy and the class variable is the same copy for all objects of the class • Object not needed to reference a class variable 19 Blue Ridge Junior College
  • 20. Scope and Visibility Rules – cont. • Local Variables • A local variable is the one that is declared within a method or a constructor (not in the header) • The scope and lifetime are limited to the method itself • In addition to the local variables defined in a method, we also have variables that are defined in blocks like an if block and an else block • The scope and life is the same as that of the block itself 20 Blue Ridge Junior College
  • 21. Scope and Visibility Rules – cont. • Local Variables public class Dog { public void putAge() { int age = 0; //local variable age = age + 6; System.out.println("Dog age is : " + age); } public static void main(String args[]){ Dog d = new Dog(); d.putAge(); } } • Here, age is a local variable • This variable is defined under putAge() method and its scope is limited to this method only 21 Blue Ridge Junior College
  • 22. Scope and Visibility Rules – cont. • Local Variables • In Java, we can create nested blocks – a block inside another block. • All the local variables in the outer block are accessible within the inner block but vice versa is not true i.e., local variables within the inner block are not accessible in the outer block public static void main(String[] args) { int x; //Begining of inner block { int y = 100; x = 200; System.out.println("x = "+x); } //End of inner block System.out.println("x = "+x); y = 200; //Error as y is not accessible in the outer block } } • As you can see in the above program, an error is generated as the variable ”y” is not visible in the outer block and therefore cannot be accessed 22 Blue Ridge Junior College
  • 23. Scope and Visibility Rules – cont. • Formal Parameters or Argument variables • These are the variables that are defined in the header of constructor or a method • The scope of these variables is the method or constructor in which they are defined • The lifetime of these variables is limited to the time for which the method keeps executing • Once the method finishes execution, these variables are destroyed 23 Blue Ridge Junior College
  • 24. Scope and Visibility Rules – cont. • Formal Parameters or Argument variables public class Test { private int num; public void method(int x) { num=x; } public static void main(String args[]) { Test t = new Test(); t.method(5); } } 24 Blue Ridge Junior College
  • 25. What are Functions? • A Java method or a function is a collection of statements that are grouped together to perform an operation • Technically, a function is a subprogram within a main program, which processes data and returns a value • Each function has a unique name with which it is called within a program • A method or function can be called (invoked) at any point in a program simply by utilizing the method's / function’s name 25 Blue Ridge Junior College
  • 26. What are Functions? – cont. • As stated earlier, each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method • When the method is completed, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code 26 Blue Ridge Junior College
  • 27. Need for Functions • When you start writing real programs, you would realize that they can grow to many pages of code • A full-length program contains many pages of code, and trying to find a specific part of the program in all that code can be tough • When programs get long, they also get harder to organize and read • To overcome this problem, professional programmers break their programs down into individual functions, each of which completes a specific and well-defined task 27 Blue Ridge Junior College
  • 28. Need for Functions – cont. • Using modular programming techniques, you can break a long program into individual modules, each of which performs a specific task • When you break your program's modules down into even smaller modules, you are using a top-down approach to program design • By using top-down programming techniques, you can write any program as a series of small, easy-to- handle tasks • In Java, the basic unit for organizing code in a top- down manner is the function 28 Blue Ridge Junior College
  • 29. Need for Functions – cont. • Functions are time savers, in that they allow for the repetition of sections of code without retyping the code • In addition, functions can be saved and utilized again and again in newly developed programs • The use of methods will be our first step in the direction of modular programming 29 Blue Ridge Junior College
  • 30. Defining Functions • The general format of defining function in a java class is as follows: • [access specifier][static][return type] function- name (formal parameters) • access specifier: It defines the access type of the method. This can be public, private, protected or default. By default, functions have public access specifier • static: The static keyword enables the function to be called without creating an object • return-type: The data type of the value returned by the method, or void if the method does not return a value 30 Blue Ridge Junior College
  • 31. Defining Functions – cont. • function-name: This is the name of the function • formal parameters: The list of parameters - it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters. If there are no parameters, you must use empty parentheses • function body: The set of statements that would get executed when the function is called. 31 Blue Ridge Junior College
  • 32. Defining Functions – cont. • function-header: This is the first line which contains the access specifier, return type, function name and list of parameters. • formal signature: A method signature is written by using the method name along with the parameters to be passed to the method. Example of method signature: test(int a, int b) 32 Blue Ridge Junior College
  • 33. Defining Functions – cont. • Naming a Method / Function • Although a method name can be any legal identifier, code conventions restrict method names • By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. • In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples: • run • runFast • getBackground • getFinalData 33 Blue Ridge Junior College
  • 34. Defining Functions – cont. • A method's declaration provides a lot of information about the method to the compiler, the runtime system and to other classes and objects • Besides the name of the method, the method declaration carries information such as the return type of the method, the number and type of the arguments required by the method, and what other classes and objects can call the method 34 Blue Ridge Junior College
  • 35. Classification of Functions • A Java program is basically a set of classes • A class is defined by a set of declaration statements and methods or functions • Java programming supports different types of function as in User Defined Function (UDF)(A function which is created by user so it is known as user defined function) and also there are some functions available within the Java packages that provide some imperative support to the java programmer for developing their programming logic as well as their programming architecture 35 Blue Ridge Junior College
  • 36. Classification of Functions – cont. • Predefined Functions • The Java API or application programming interface is a collection of software packages that programmers can use for graphics, user interface, networking, sound, database, math, and much more • It contains many methods that have already been written and tested • In order to use these specific methods in our program we have to import the necessary libraries by adding them to our program 36 Blue Ridge Junior College
  • 37. Classification of Functions – cont. • User Defined Functions • Functions defined by the programmer within the program to use it for a particular task • User defined function is totally based on the user control • When we create user define function name then we must remember some special point that points are given below • We cannot use any reserved keywords • We can use the same function name for the different numbers of types of arguments list • So, we can overload our user-defined functions in our system • The function name can only comprehend letters, numbers, and the underscore (_) • Function name must start with a letter • The function names which cannot be exceed 128 characters 37 Blue Ridge Junior College
  • 38. Classification of Functions – cont. • Functions are mostly used to produce some computational output • Actions inside a function may be like reading and displaying some data values; assigning or modifying some existing values; computing and returning a result for further use, etc. • Out of all such actions, some operations like write or modify can disturb or change the value of some already stored member-data. Therefore, write or update operations are to be treated very carefully and unrestricted public access should not be allowed • On the other hand, read or display operations are not destructive, because read operations do not change data values. So no access restriction will be necessary for such operations • Based on the operational side effects, functions can be classified as either pure functions or impure functions 38 Blue Ridge Junior College
  • 39. Classification of Functions – cont. • Pure Functions • A pure function, when invoked, does not cause any change in the state of an object, that means there will be no change in the values of the object’s instance variables • For example readData() or getData() functions can be treated as pure functions as they do not change any existing data values • Pure functions can safely be declared as public also 39 Blue Ridge Junior College
  • 40. Classification of Functions – cont. • Pure Functions • Code snippet for pure function: class add { void sum(int a, int b) { int c = calc(a,b); System.out.println(“The sum is” +c); } int calc(int a, int b) { int c=a+b; return(c); } } When a method contains a return statement, it is always the final statement of that method, because no further statements in the method will be executed once the return statement is executed 40 Blue Ridge Junior College
  • 41. Classification of Functions – cont. • Impure Functions • Impure functions, also called modifier functions, are those that can cause a change of state in the object • Values of the object’s instance variables get modified or changed depending on the current state of the object on which the function operates • Such functions can cause some unwanted side effects if not carefully controlled by the access-modifier 41 Blue Ridge Junior College
  • 42. Classification of Functions – cont. • Impure Functions • Demonstration of an Impure Function public class ImpureFncTest { String name; int accNo; double accBalance; double withdrawVal; public double transaction(double balance, double withdraw) { if ( withdraw > balance) {System.out.println("Sorry !! Transaction Impossible.");} else {balance = balance - withdraw;System.out.println("Transaction Successful.");} return balance ;} public void show( double bal){ System.out.println ( "Balance Available : " + bal);} public static void main() {// manipulation of the first object ImpureFncTest customer1 = new ImpureFncTest();//first object customer1.name = " Anita Kar"; customer1.accNo = 8912; customer1.accBalance = 123456.50; customer1.withdrawVal = 5000.00; System.out.println ( customer1.name + " -- Account No. :: " + customer1.accNo);customer1.accBalance = customer1.transaction(customer1.accBalance,customer1.withdrawVal);customer1. show(customer1.accBalance); // manipulation of the second object ImpureFncTest customer9 = new ImpureFncTest();//second object customer9.name = " Kalyan Bhatt"; customer9.accNo = 13245; customer9.accBalance = 3592.75; customer9.withdrawVal = 4000.00; System.out.println ( customer9.name + " -- Account No. :: " + customer9.accNo);customer9.accBalance = customer9.transaction(customer9.accBalance,customer9.withdrawVal);customer9. show(customer9.accBalance); } } 42 Blue Ridge Junior College
  • 43. Classification of Functions – cont. • Impure Functions • In this example, transaction (double, double) is an impure function, because it causes a change in the object’s state by changing the value of the Balance Available 43 Blue Ridge Junior College
  • 44. Classification of Functions– cont. • Function can also be classified as follows depending upon the function definition: • Function which does not have argument or a return type • Function which has an argument but no return type • Function which has no argument but has a return type • Function which has both an argument and return type 44 Blue Ridge Junior College
  • 45. Classification of Functions – cont. • To understand this concept, we need to first cover returning values from a function • A method returns to the code that invoked it when it • completes all the statements in the method, • reaches a return statement, or • throws an exception (covered later), whichever occurs first You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. 45 Blue Ridge Junior College
  • 46. Classification of Functions – cont. • Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so • In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: • return; • If you try to return a value from a method that is declared void, you will get a compiler error. • Any method that is not declared void must contain a return statement with a corresponding return value, like this: • return returnValue; • The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean 46 Blue Ridge Junior College
  • 47. Classification of Functions – cont. • Function which does not have argument or a return type • Such functions do not have any argument and the return type is void as the function only performs activities like computation and printing class ABC { void add() { int a=10; int b=20; int c=a+b; System.out.println(c); } } The void keyword allows us to create methods which do not return a value 47 Blue Ridge Junior College
  • 48. Classification of Functions – cont. • Function which has an argument but no return type • Such functions may have single or multiple arguments and return nothing class ABC { void add(int a, int b) { int c=a+b; System.out.println(c); } } • When passing arguments or parameters to a method, it should be in the same order as their respective parameters in the method specification 48 Blue Ridge Junior College
  • 49. Classification of Functions – cont.  Function which has no argument but has a return type  Such functions do not have any argument but return a value using the return keyword class ABC { int add() { int a=10; int b=20; int c=a+b; return c; } } 49 Blue Ridge Junior College
  • 50. Classification of Functions – cont.  Function which has both an argument and return type class ABC { int add(int a, int b) { int c=a+b; return c; } } 50 Blue Ridge Junior College
  • 51. Calling and Accessing Functions • Methods don't do anything until you call them into action • The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method • This called method then returns control to the caller in two conditions, when − • the return statement is executed. • it reaches the method ending closing brace 51 Blue Ridge Junior College
  • 52. Calling and Accessing Functions • The main() function gets executed first and then the other functions are called • All functions contained within the main() function are called sub-functions • A function can be called in two ways depending upon the main() function • Functions that are within the same class as the main() method: • In this case, the function can be directly called by the main() method without needing an object to do so 52 Blue Ridge Junior College
  • 53. Calling and Accessing Functions • Example: public class ExampleMinNumber { public static void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.println("Minimum Value = " + c); } /** returns the minimum of two numbers */ public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } } 53 Blue Ridge Junior College
  • 54. Calling and Accessing Functions • Functions that are in a different class from the class with the main() method • In this case, the function can be called by the main() method in two ways: • If the method is static, it can be called using the classname and the dot operator class Student { int rollno; static String college = "ITS"; static void change() { college = "BBDIT"; } public static void main(String args[]) { change(); //main of the same class } } //end of class Student class Test { public static void main(String args[]) { Student.change(); //calling function of another class } } 54 Blue Ridge Junior College
  • 55. Calling and Accessing Functions • If the method is non static, then we create an object and call the method using the dot operator on the object class Student1{ int rollno; String name; String college = "ITS"; Student1(int r, String n) { rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } }// end of class Student1 class Test1 { int a=5; public static void main(String args[]) { Student1 s = new Student1 (111,"Karan"); //creating object for Student1 class s.display(); //calling method of another class } } 55 Blue Ridge Junior College
  • 56. Function Overloading • Function Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different • Overloading always occurs in the same class • Method overloading is one of the ways through which Java supports polymorphism • Method overloading can be done by changing number of arguments or by changing the data type of arguments • If two or more methods have the same name and same parameter list but differ in return type, they are not said to be overloaded method 56 Blue Ridge Junior College
  • 57. Function Overloading – cont. • When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call • Thus, overloaded methods must differ in the type and/or number of their parameters • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call 57 Blue Ridge Junior College
  • 58. Function Overloading – cont. • Need for Function Overloading • Using the concept of function overloading, a family of functions can be designed , with one function name but different parameter lists • This is how java supports polymorphism using function overloading, "one interface, multiple methods paradigm‘ • One benefit of overloading is that you can access related methods by using common name • Function overloading avoids coding error if there are different methods names and a wrong method is coded by the programmer 58 Blue Ridge Junior College
  • 59. Function Overloading – cont. • 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 TestOverloading { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); } } • In this example, we have created two methods, first add() method performs addition of two numbers and second add() method performs addition of three numbers • In this example, we have creating static methods so that we don't need to create instance for calling methods 59 Blue Ridge Junior College
  • 60. Function Overloading – cont. • Changing data type of arguments class Adder { static int add(int a, int b) { return a+b; } static double add(double a, double b) { return a+b; } } class TestOverloading { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); } } • In this example, we have created two methods that differs in data type • The first add method receives two integer arguments and second add method receives two double arguments 60 Blue Ridge Junior College
  • 61. Recursive Function • A function designed in such a way that it calls itself in its body is called Recursive Function 61 Blue Ridge Junior College
  • 62. Objects as Parameters • We can pass object of any class as parameter to a method in Java • For example, consider the following program: class Rectangle { int length; int width; Rectangle(int l, int b) { length = l; width = b; } void area(Rectangle r1) { int areaOfRectangle = r1.length * r1.width; System.out.println("Area of Rectangle : " + areaOfRectangle); } } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(10, 20); r1.area(r1); } } Output of the program : Area of Rectangle : 200 62 Blue Ridge Junior College
  • 63. Objects as Parameters – cont. • We can access the instance variables of the object passed inside the called method • Like area = r1.length * r1.width • It is a good practice to initialize instance variables of an object before passing object as parameter to the method. Otherwise it will take the default initial values 63 Blue Ridge Junior College
  • 64. Objects as Parameters – cont. • Call by Value and Call by Reference • Before we look into what the terms call by value and call by reference mean, let us look at two simple programs and examine their output: class CallByValue { public static void main ( String[] args ) { int x =3; System.out.println ( "Value of x before calling increment() is "+x); increment(x); System.out.println ( "Value of x after calling increment() is "+x); } public static void increment ( int a ) { System.out.println ( "Value of a before incrementing is "+a); a= a+1; System.out.println ( "Value of a after incrementing is "+a); } } The output of this program would be: Value of x before calling increment() is 3 Value of a before incrementing is 3 Value of a after incrementing is 4 Value of x after calling increment() is 3 64 Blue Ridge Junior College
  • 65. Objects as Parameters – cont. • As is evident from the output, the value of x has remain unchanged, even though it was passed as a parameter to the increment() method • And now, we move on to the second program, where we will make use of class Number that contains a single instance variable x class Number { int x; } class CallByReference { public static void main ( String[] args ) { Number a = new Number(); a.x=3; System.out.println("Value of a.x before calling increment() is "+a.x); increment(a); System.out.println("Value of a.x after calling increment() is "+a.x); } public static void increment(Number n) { System.out.println("Value of n.x before incrementing x is "+n.x); n.x=n.x+1; System.out.println("Value of n.x after incrementing x is "+n.x); } } This program would give the following output Value of a.x before calling increment() is 3 Value of n.x before incrementing x is 3 Value of n.x after incrementing x is 4 Value of a.x after calling increment() is 4 65 Blue Ridge Junior College
  • 66. Objects as Parameters – cont. • In the first program, the change made to the variable a inside the increment() method had no effect on the original variable x that was passed as an argument • On the other hand, in the second program, changes made to the variable x that was a part of the object in the increment() method had an effect on the original variable ( the object which contained that integer variable) that was passed as an argument • The difference lies in the type of the variable that was passed as an argument • int is a primitive data type while Number is a reference data type • Primitive data types in Java are passed by value while reference data types are passed by reference 66 Blue Ridge Junior College
  • 67. Objects as Parameters – cont. • What we mean by passing a variable by value is that the value held in the variable that is passed as an argument is copied into the parameters that are defined in the method header • That is why changes made to the variable within the method had no effect on the variable that was passed • On the other hand, when objects are passed, the object itself is passed • No copy is made. Therefore changes made to the object within the method increment() had an effect on the original object 67 Blue Ridge Junior College
  • 68. Objects as Parameters – cont. • The following figure illustrate call be reference and call by value 68 Blue Ridge Junior College
  • 69. Objects as Parameters – cont. • The concept of call by reference can be better understood if one tries to look into what a reference actually is and how a variable of a class type is represented • When we declare a reference type variable, the compiler allocates only space where the memory address of the object can be stored. The space for the object itself isn't allocated • The space for the object is allocated at the time of object creation using the new keyword • A variable of reference type differs from a variable of a primitive type in the way that a primitive type variable holds the actual data while a reference type variable holds the address of the object which it refers to and not the actual object. 69 Blue Ridge Junior College
  • 70. Static Members and Functions • static is a Java keyword. It can be applied to a field, a method or an inner class • If you declare any variable as static, it is known as a static variable • The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves • The static variable gets memory only once in class area at the time of class loading • So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances 70 Blue Ridge Junior College
  • 71. Static Members and Functions – cont. • Java static variable • It is a variable which belongs to the class and not to object(instance) • Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables • A single copy to be shared by all instances of the class • A static variable can be accessed directly by the class name and doesn’t need any object • Syntax : <class-name>.<variable-name> 71 Blue Ridge Junior College
  • 72. Static Members and Functions – cont. • Java Static Functions • It is a method which belongs to the class and not to the object(instance) • A static method can access only static data. It can not access non- static data (instance variables) • A static method can call only other static methods and can not call a non-static method from it. • A static method can be accessed directly by the class name and doesn’t need any object • Syntax : <class-name>.<method-name> 72 Blue Ridge Junior College
  • 73. Static Members and Functions – cont. • Understanding problem without static variables class Student{ int rollno; String name; String college="ITS"; } • Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created • All student have its unique rollno and name so instance data member is good • Here, college refers to the common property of all objects • If we make it static, this field will get memory only once. 73 Blue Ridge Junior College
  • 74. Static Members and Functions – cont. class Student{ int rollno; String name; static String college ="IIT"; Student(int r,String n){ rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } public static void main(String args[]){ Student s1 = new Student(111,“Raj"); Student s2 = new Student(222,“Shubham"); s1.display(); s2.display(); } } Output: 111 Raj IIT 222 Shubham IIT 74 Blue Ridge Junior College
  • 75. Static Members and Functions – cont. • Difference between Static variables and Instance variables: • Static variables and instance variables both are member variables because they are both associated with a specific class, but the difference between them is Static variables has only one copy that is shared by all the different objects of a class, whereas every object has its own personal copy of an instance variable • So, instance variables across different objects can have different values whereas static variables across different objects can have only one value • Both are declared at class level outside any method • Static variables are also called class variables 75 Blue Ridge Junior College
  • 76. What are Constructors? • A constructor in Java is a block of code similar to a method that is called when an instance of an object is created • It is a special method that is used to initialize a newly created object • Java constructor is invoked at the time of object creation • It constructs the values i.e. provides data for the object that is why it is known as constructor 76 Blue Ridge Junior College
  • 77. What are Constructors – cont. • Key differences between a constructor and a method • A constructor doesn’t have a return type (not even void) since the basic aim is to place the value in the object. If we write the return type for the constructor then that constructor will be treated as ordinary method • The name of the constructor must be the same as the name of the class • Constructor definitions should not be static as constructors will be called each and every time, whenever an object is created 77 Blue Ridge Junior College
  • 78. What are Constructors – cont. • Unlike methods, constructors are not considered members of a class • A constructor is called automatically when a new instance of an object is created 78 Method Constructor Method can be any user defined name Constructor must be class name Method should have return type It should not have any return type (even void) Method should be called explicitly either with object reference or class reference It will be called automatically whenever object is created Method is not provided by compiler in any case The java compiler provides a default constructor if we do not have any constructor Blue Ridge Junior College
  • 79. Need for Constructors • It can be cumbersome to initialize all variables in a call each time an instance of a class in created • Constructors are mainly created for initializing the object • Initialization is a process of assigning user defined values at the time of allocation of memory space • An advantage of constructors in Java is it eliminates placing the default values 79 Blue Ridge Junior College
  • 80. Need for Constructors – cont. • Whenever we create an object of any class, memory is allocated memory for all the data members and their values are initialized to their default values • To eliminate these default values by user defined values we use constructor 80 Blue Ridge Junior College
  • 81. Constructor Example class Programming { //constructor method Programming() { System.out.println("Constructor method called."); } public static void main(String[] args) { Programming object = new Programming(); //creating object } } 81 Blue Ridge Junior College
  • 82. Types of Constructors • Based on creating objects in Java, constructor are classified in two types. They are: • Default or no argument Constructor • Parameterized Constructor 82 Blue Ridge Junior College
  • 83. Types of Constructors – cont.  Default or no argument Constructor • A constructor that has no parameter is known as default constructor • If we do not define a constructor in a class, then compiler creates default constructor(with no arguments) for the class • If we write a constructor with arguments or no-argument then compiler does not create default constructor Default constructor provides the default values to the object like 0, null etc. depending on the type 83 Blue Ridge Junior College
  • 84. Types of Constructors – cont. • Example of default constructor • In this example, we are creating the no-argument constructor in the Bike class • It will be invoked at the time of object creation class Bike { Bike() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike b=new Bike (); } } 84 Blue Ridge Junior College
  • 85. Types of Constructors – cont. • If there is no constructor in a class, compiler automatically creates a default constructor • The default constructor is a constructor that the Java compiler adds to your code if no explicit constructor is available • If you have added your own constructor (no matter whether it's without parameters or with parameters) the compiler will not add the default constructor in this case 85 Blue Ridge Junior College
  • 86. Types of Constructors – cont. • Parameterized Constructor • A constructor that has parameters is known as parameterized constructor • If we want to initialize fields of the class with your own values, then use parameterized constructor • This type of constructor accepts parameters and initializes the data members based on the arguments passed to it • A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters public void MyMethod(String myParam) { } ... String myArg1 = "this is my argument"; myClass.MyMethod(myArg1); 86 Blue Ridge Junior College
  • 87. Types of Constructors – cont. • Example of parameterized constructor class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display() { System.out.println(id+" "+name); } public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } • In this example, we have created the constructor of Student class that has two parameters • We can have any number of parameters in the constructor 87 Blue Ridge Junior College
  • 88. Constructor Overloading • Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists • Like methods, we can overload constructors for creating objects in different ways • Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters and order of the parameters 88 Blue Ridge Junior College
  • 89. Constructor Overloading – cont. • Example of Constructor Overloading class Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } 89 Blue Ridge Junior College
  • 90. Constructor Overloading – cont. class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); } Demo(int a){ value1 = a; System.out.println("Inside 2nd Constructor"); } Demo(int a,int b){ value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); } } 90 Output Blue Ridge Junior College