Professional Documents
Culture Documents
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Constructor Methods, Nested Classes, Final Class and Methods,
Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor
Methods, Recursive Methods, Nesting of Methods, Overriding Methods, Attributes Final and
Static.
2.1 Classes and Objects Introduction
Classes:
• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created.
• Classes are user-defined data types and behave like the built-in types of a programming
language.
• It is a logical entity. It can't be physical. In the real-world, classes are invisible only
objects are visible.
• A class in Java can contain: Fields, Methods, Constructors, Blocks, Nested class and
interface.
• Example: Student
Properties-->name,rollno,height,color-->Fields or variable
Action-->Run(),Read(),Write(),sleep()---> Methods
Objects:
• An object is an instance of a class. An entity that has state and behavior is known as an
object e.g., chair, bike, marker, pen, table, car, Person, Place, bank account, …., so on.
• An object is a physical entity, that entity that has physical existence.
• An object is a runtime entity. The object is an entity which has state and behavior.
• The most important benefits of an objects are Modularity and Reusability.
• The properties of objects are two types visible and invisible.
• Let man is an object, then visible properties are eyes, ears, hands, legs,…so on and
invisible properties are name, blood group,…. so on.
• Every object contains three basic elements Identity (name), State (variables) and
Behavior (methods)
2.2 Class Declaration and Modifiers
Class Declaration:
A class declaration starts with the Access modifier. It is followed by keyword class,
which is followed by the name or identifier. The body of class is enclosed between a pair of
braces { }.
Syntax: Class Identifier
Modifier class Identifier
{
Class Modifier /*Class Members- fields, methods, classes, interfaces */
}
Example:
public class MyFarm
{
double length; //instance variable
double width; //instance variable
}
• Modifiers: A class can be public or has default access (Refer this for details).
• class keyword: class keyword is used to create a class.
• Class Identifier: The name should begin with an initial letter.
• Body: The class body surrounded by braces, { }.
• The class name starts with an upper-case letter, whereas variable names may start win
lower-case letters.
• In the case of names consisting of two or more words as in MyFarm, the other words for
with a capital letter for both classes and variables. In multiword identifiers, there is no
blank space between the words
• Class names should start with an upper-case letter and should be nouns. For example, it
could include names such as vehicles, books, and symbols.
• It should have both upper and lower-case letters with the first letter capitalized.
Class Modifiers:
• Class modifiers are used to control the access to class and its inheritance characteristics.
• Java consists of packages and the packages consist of sub-packages and classes Packages
can also be used to control the accessibility of a class.
• These modifiers can be grouped as
(a) access modifiers→ No modifier, public, private and protected.
(b) non-access modifiers→final and abstract
Examples:
1. A class without modifier.
class Student
{
/* class body*/
}
2. A class with modifier
public class Student
{
/* class body*/
}
2.3 Class Members
The class members are declared in the body of a class. These may comprise fields
(variables in a class). methods, nested classes, and interfaces.
The fields comprise two types of variables
1. Non-Static variables: These include instance and local variables and vanes in scope and
value.
• Instance variables: These variables are individual to an object and an object keeps a
copy of these variables in its memory.
• Local variables: These are local in scope and not accessible outside their scope.
2. Class variables (Static Variables): These variables are also qualified as static variables.
The values of these variables are common to all the objects of the class. The class keeps
only one copy of these variables and all the objects share the same copy. As class
variables belong to the whole class, these are also called class variables.
2.4 Declaration of Class Objects
Creating an object is also referred to as instantiating an object.
• Objects in java are created dynamically using the new operator. The new operator creates
an object of the specified class and returns a reference to that object.
• Syntax: - class-name object-name=new class-name():
Example 1:
class CustomerId
{
static int count=0; // static variable
int id; // instance variable
CustomerId() // Constructor
{
count++;
id = count ;
}
int getId() // Method
{
return id;
}
int localVar()
{
int a=10; //Local variable
return a;
}
}
class Application
{
public static void main(String[] args)
{
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId());
System.out.println("Local Variable = " + obj.localVar());
}
}
Output:
C:\>javac Application.java
C:\>java Application
Customer Id = 1
Local Variable = 10
Example 2:
class Rectangle
{
double l,b; //instance variable
double area()
{
return l*b;
}
public static void main(String args[])
{
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
//Assign value to rect1 instance variable
rect1.l = 10;
rect1.b = 20;
//Assign value to rect2 instance variable
rect2.l = 30;
rect2.b = 40
System.out.println(“Area of Rectangle1=”+rect1.area());
System.out.println(“Area of Rectangle2=”+rect2.area());
}
}
Output
Area of Rectangle1= 200
Area of Rectangle2= 1200
Note: we can access the members of a class using object name and .(dot) operator
2.5 Constructor Methods
• A constructor is a special method of the class and it is used to initialize an object
whenever the object is created.
• It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
• We can create object with the help of constructor, without constructor object creation is
not possible
Rules for creating Java Constructor
A Constructor is a special method because,
• Class name and Constructor name both must be same
• Doesn’t contain any return type
• Automatically executed when object is created.
Types of Java Constructors
There are two types of constructors in Java:
1. Default Constructor (no-arg constructor)
2. Parameterized Constructor
1. Default Constructor (no-arg constructor)
The Java compiler automatically create a no-arg constructor during the execution of the
program. This constructor is called default constructor.. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.
Syntax of default constructor:
<class_name>(){}
Example1 of default constructor that displays the default values
//Let us see another example of default constructor
//which displays the default values
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Example2
/* Here, Box uses a constructor to initialize the dimensions of a box. */
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
2. Parameterized constructor
A constructor which has a specific number of parameters is called a parameterized
constructor. The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Add class that have two parameters.
We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Add
{
int a,b,total;
//creating a parameterized constructor
Add(int x,int y)
{
a=x;
b=y;
}
//method to display the values
void sum()
{
total=a+b;
System.out.println("Sum="+total);
}
}
class Madd
{
public static void main(String args[])
{
//creating objects and passing values
Add obj1=new Add(20,30);
Add obj2=new Add(50,60);
Add obj3=new Add(100,200);
//calling method to display the values of object
obj1.sum();
obj2.sum();
obj3.sum();
}
}
Output
Sum=50
Sum=110
Sum=300
2.6 Constructor Overloading
Constructor overloading means within the same class writing two or more constructor
with same name but different parameters. What are the different parameters?
1. Number of Parameters
Ex: add(int)
add(int,int)
add(int,int,int)
2. Type of Parameter
Ex: add(int,int)
add(double,double)
3. Order of Parameter
Ex: add(int,double)
add(double,int)
Example of Constructor Overloading
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
2.7 Methods Introduction
• A method in Java represents an action on data or behaviour of an object. In other
programming languages, the methods are called functions or procedures.
• A method is a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation.
• It is used to achieve the reusability of code. We write a method once and use it many
times. We do not require to write code again and again.
• It also provides the easy modification and readability of code, just by adding or removing
a chunk of code.
Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method
1. Predefined Method
predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
Example of the predefined method.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output: - The maximum number is: 9
2. User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
Types of Methods
• Default Method
• Parametrized Method
2.8 Defining Methods
A method definition comprises two components:
• Header that includes modifier, type, identifier, or name of method and a list of
parameters. The parameter list is placed in a pair of parentheses.
• Body that is placed in braces ({ }) and consists of declarations and executable statement
and other expressions.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our
application.
• Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
• Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
• Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Default Method
Example: -
Adding a Method to the Box Class (Without Return Value)
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of first box
mybox1.volume();
}
}
Output:- Volume is 3000.0
Adding a Method to the Box Class (Returning a Value)
A Java method may or may not return a value to the function call. We use the return
statement to return any value. For example,
int addNumbers()
{
...
return sum;
}
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output
Volume is 3000.0
Volume is 162.0
Parametrized Method
A method parameter is a value accepted by the method. As mentioned earlier, a method
can also have any number of parameters. For example,
// method with two parameters
int addNumbers(int a, int b)
{
// code
}
// method with no parameter
int addNumbers()
{
// code
}
If a method is created with parameters, we need to pass the corresponding values while
calling the method. For example,
// calling the method with two parameters
addNumbers(25, 15);
// calling the method with no parameters
addNumbers()
Example for Method Parameters
class Main
{
// method with no parameter
public void display1()
{
System.out.println("Method without parameter");
}
// method with single parameter
public void display2(int a)
{
System.out.println("Method with a single parameter: " + a);
}
public static void main(String[] args)
{
// create an object of Main
Main obj = new Main();
// calling method with no parameter
obj.display1();
// calling method with the single parameter
obj.display2(24);
}
}
Output
Method without parameter
with a single parameter: 24
2.9 Overloaded Methods
• Method overloading means within the same class writing two or more methods with same
name but different signatures (parameters).
• What are the different parameters?
1. Number of Parameters
Ex: void add(int)
void add(int,int)
void add(int,int,int)
2. Type of Parameter
Ex: int add(int,int)
int add(double,double)
3. Order of Parameter
Ex: double add(int,double)
double add(double,int)
• The compiler executes the version of the method whose parameters match with the
arguments.
• Method overloading is one of the ways that Java supports polymorphism.
Example of Method Overloading
Here is a simple example that illustrates method overloading:
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
2.10 Recursive Methods
• A Method which is calling itself is called as Recursive Method. Recursion in java is a
process in which a method calls itself continuously.
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
Example:
class Fact
{
int factorial (int n)
{
if(n<2)
return n;
else
return n*(factorial(n-1));
}
}
class FactDemo
{
public static void main(String[] args)
{
Fact obj =new Fact();
int n=5;
int res = obj.factorial(n);
System.out.println("Factorial of " + n + " = " +res);
}
}
Output:
C:\>javac FactDemo.java
C:\>java FactDemo
Factorial of 5 = 120
2.11 Nesting of Methods
• A method calling in another method with in the class is called as Nesting of Methods.
Example:
class Rectangle
{
void perimeter(int l, int w)
{
System.out.println("Length ="+l+", Width= "+w);
System.out.println("Perimeter = " + (l+w));
}
void area(int l, int w)
{
perimeter(l,w); // Nesting of Method
System.out.println("Area = " + (l*w));
}
}
class RectangleDemo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.area(5,4);
}
}
Output:
C:\ >javac RectangleDemo.java
C:\ >java RectangleDemo
Length =5, Width= 4
Perimeter = 9
Area = 20
2.12 Nested (Inner) Classes
• Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
• A nested class is also a member of its enclosing class. As a member of its enclosing class,
a nested class can be declared private, public, protected, or package private(default).
• Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
• Nested classes are divided into two categories:
1. static nested class : Nested classes that are declared static are called static nested
classes.
2. inner class : An inner class is a non-static nested class.
a. Member inner class
b. Local inner class
c. Anonymous inner class
Static nested class
A static class is a class that is created inside a class, is called a static nested class in
Java. It cannot access non-static data members and methods. It can be accessed by outer class
name.
• It can access static data members of the outer class, including private.
• The static nested class cannot access non-static (instance) data members
Example
class TestOuter1
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output
data is 30
Member Inner Class
• A class which is declared within class but outside a method is called Member inner class.
• The inner class has access to all the members of the enveloping class including the
members declared public, protected or private.
Example:
class Outer
{
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}