Java R19 - UNIT-2
Java R19 - UNIT-2
8. Nesting of Methods
Object = Data + Methods
9. Overriding Methods
10. Attributes Final and Static. 2. Class Declaration and Modifiers
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:
Example:
The class name starts with an upper-case letter, whereas variable names may start win
lower-case letters. Examples:
In the case of names consisting of two or more words as in MyFarm, the other words for 1. A class without modifier.
with a capital letter for both classes and variables. In multiword identifiers, there is no class Student
blank space between the words {
The class names should be simple and descriptive. /* class body*/
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. 2. A class with modifier
It should have both upper and lower-case letters with the first letter capitalized public class Student
Acronyms and abbreviations should be avoided {
/* class body*/
Class modifiers: }
Class modifiers are used to control the access to class and its inheritance characteristics. (or)
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 private class Student
These modifiers can be grouped as (a) access modifiers and (b) non-access modifiers. {
Table 5.l gives a description of the various class modifiers. /* class body*/
}
(or)
(or)
Example:
final class Student
{ class CustomerId
/* class body*/ {
} static int count=0; // static variable
int id; // instance variable
(or) CustomerId() // Constructor
{
abstract class Student count++;
{ id = count ;
/* class body*/ }
} int getId() // Method
{
3. Class Members return id;
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 members of a class comprise the members int localVar()
declared in the class as well as the members inherited from a super class. The scope of all the {
members extends to the entire class body. int a=10; //Local variable
The fields comprise two types of variables
return a;
}
}
1. Non Static variables : These include instance and local variables and vanes in scope and
value.
class Application
(a) Instance variables: These variables are individual to an object and an object keeps a {
copy of these variables in its memory. public static void main(String[] args)
(b) Local variables: These are local in scope and not accessible outside their scope. {
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId());
2. Class variables ( Static Variables) : These variables are also qualified as static variables.
System.out.println("Local Variable = " + obj.localVar());
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. }
Output:
C:\>javac Application.java
C:\>java Application
Customer Id = 1
Local Variable = 10
4. Declaration of Class Objects 5. Assigning One Object to Another
Creating an object is also referred to as instantiating an object. Java provides the facility to assign one object to another
- Objects in java are created dynamically using the new operator. object
- The new operator creates an object of the specified class and returns a reference to that
object. Syntax:
Syntax: (creating an object)
new_Object = old_object;
className objectReference=new className();
all the properties of old_object will be copied to new object.
Example:
class Farm
{
double length;
double width;
double area()
{
return length*width;
}
}
public class FarmExel
{
public static void main (String args[])
{
Farm farm1 = new Farm(); //defining an object of Farm
Farm farm2 = new Farm(); //defining new object of Farm
farm1.length = 20.0;
farm1.width = 40.0;
Example:
System.out.println("Area of form1= " + farm1.area());
Farm myFarm = new Farm();
farm2 = farm1; // Object Assignment
}
}
Output:
C:\>javac FarmExel.java
C:\>java FarmExel
Area of form1= 800.0
Area of form2 = 800.0
class FarmExe3
6. Access Control for Class Members {
In Java, There are three access specifiers are permitted: public static void main (String args[])
{
• public
• protected Farm farm1 =new Farm();
• private double farmArea;
The coding with access specifiers for variables is illustrated as
farm1.setSides(50.0,20.0);
Access_specifier type identifier; farmArea = farm1.area();
Detials of Access specifiers are as follows.
System.out.println("Area of farm1 = "+ farmArea);
System.out.println("Length of farm1 = "+ farm1.getLength());
System.out.println("Length of farm1 = "+ farm1.getWidth());
}
}
Output
C:\>javac PrivateMembers.java
C:\>java FarmExe3
Area of farm1 = 1000.0
7. Accessing Private Members of Class Length of farm1 = 50.0
Length of farm1 = 20.0
Private members of a class, whether they are instance variables or methods, can only be
accessed by other members of the same class In the above program, the two object variables length and width are declared private. The
Any outside code cannot directly access them because they are private. However, first thing is to assign values to these variables for an object. This is done by defining a public
interface public method members may be defined to access the private members method setSides(), which is invoked by the class object for entering values that are passed
The code other than class members can access the interface public members that pass on to length and width variables The method setsides may be defined as
the values. public void setsides (int 1, int w){length = 1; width = w;}
Example: The class also defines another method area() to which the values are passed for calculation
of area when the method area() is invoked by the object. For obtaining values of length and
public class Farm width by outside code, two public methods are defined as
{
private double length; // private member data public double getLength(){return length;} //Function for getting length
private double width; // private member data public double getWidth(){return width;} // Function for getting width
E:\>java ConstructorDemo
No parameters
Perimeter of the Circle=62.800000000000004
Perimeter of the Rectangle=60
class NestedClassDemo
10. Nested Classes {
A nested class is one that is declared entirely in the body of another class or interface. The public static void main (String args[])
{
class, which is nested, exists only long as the enveloping class exists. Therefore, the scope of
Outer obj =new Outer(10,20);
inner class is limited to the scope of enveloping class. There are four types of nested class. obj.outer_display();
}
Nested static class is like any other static member of the enveloping class. }
i. Member Inner Class.
ii. Anonymous Class Output:
iii. Local Class C:\>javac NestedClassDemo.java
iv. Static Nested Class
C:\>java NestedClassDemo
x+y = 30.0
i. Member Inner Class.
A class which is declared within class 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
{
double outer_x;
double outer_y;
Outer (double a, double b)
{
outer_x = a;
outer_y = b;
}
double outer_add()
{
return outer_x+outer_y;
}
void outer_display()
{
Inner in = new Inner();
in.inner_display();
}
Output:
C:\1. JAVA\PPT Programs>javac CallByReference.java
Example:
class Add
{
int a,b;
void setValues(int a, int b)
{
this.a = a;
this.b = b;
}
void add()
{
System.out.println("Sum = "+ (a+b) );
}
}
class ThisKeyword
{
public static void main (String args[])
{
Modifier description is as follows.
II. Methods
1. 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.
Output:
C:\ >javac MethodDemo.java
class MethodOverload
{
public static void main (String args[])
{
Add obj= new Add();
obj.setValues(10,20); // method calling
obj.add(); // calling method without arguments
obj.add(15,30);// calling method with integer datatype arguments
obj.add(10.3, 30.4); // calling method with double datatype arguments
}
}
C:\>javac MethodOverload.java
C:\>java MethodOverload
In add() method Sum = 30
In add(int, int) Method- sum= 45
In add(double, double) MethodSum = 40.7 Example:
class AddDemo
4. Overloaded ConstructorMethods {
A constructor method is automatically called whenever a new object of the class is int a,b;
constructed. It creates and initializes the Object. AddDemo() // Constructor without arguments
{
A constructor method has the same name as the name of class to which it belongs. It has a=10;
no type and it does not return any value. It only initializes the object. b=20;
}
The constructor method may also be overloaded by changing the number of default values.
Therefore, constructors with different parameters may be declared. For the remaining // Constructor Overloading with arguments
parameters, it will pick up default values when these are not specified in the object definition. AddDemo(int x, int y)
{
a = x;
b = y;
}
class ConstructorOverload
{
public static void main (String args[])
{
AddDemo obj1= new AddDemo(); //calling constructor without arguments
obj1.add();
Output:
C:\>javac ConstructorOverload.java
C:\>java ConstructorOverload
a = 10, b = 20: Sum = 30
a = 150, b = 60: Sum = 210
5. Class Objects as Parameters in Methods iii. public
Objects can be passed as parameters to the Methods just like iv. default case-no modifier specified
primit ive data types. It is called as Call by Reference.
i. private : The private members can only be accessed by the other members
Example: (methods) of the same class. No other code outside the class can access them.
class AddDemo Ex:
{ private int x;
int a,b; private int getx()
{
void add(AddDemo obj2) // method with Object as an return x;
argument
}
{
System.out.println("Sum = "+ (obj2.a + obj2.b)
); ii. protected : The protected members can accessed by own class and derived class
} only.
} protected int x;
class ObjectAsParameters protected int getx()
{ {
public static void main (String args[])
return x;
{
AddDemo obj1= new AddDemo(); }
obj1.a=180;
obj1.b=50;
obj1.add(obj1); iii. public : The public members can accessed by all the classes.
} Ex:
} public int x;
public int getx()
Output: {
C:\>javac ObjectAsParameter.java return x;
}
C:\>java ObjectAsParameter
Sum = 230
iv. default case ( no modifier specified ): The default members can accessed by all the
classes within the package only.
6. Access Control
Java supports access control at the class level and at the level of class members. At the class
int x;
level, the following two categories are generally used:
int getx()
i. default case no modifier applied : In the default case, when no access specifier is {
applied, the class can be accessed by other classes only in the same package return x;
ii. public : A class declared public may be accessed by any other class in any package. }
In a class, Java supports the information hiding mechanism so that the user of a class does not
get to know how the process is taking place. A class contains data members and method
members or a nested class.
To access any of the members data method, or nested class-can be controlled by the
following modifiers.
i. private
ii. protected
7. Recursive Methods 8. Nesting of Methods
A Method which is calling itself is called as Recursive Method. A method calling in another method with in the class is called as Nesting of
Example: Recursive method to find factorial of a given number. Methods.
class Fact
{ Example:
int factorial (int n) class Rectangle
{ {
if(n<2) void perimeter(int l, int w)
return n; {
else System.out.println("Length ="+l+", Width= "+w);
return n*(factorial(n-1)); System.out.println("Perimeter = " + (l+w));
} }
} void area(int l, int w)
{
class FactDemo perimeter(l,w); // Nesting of Method
{ System.out.println("Area = " + (l*w));
public static void main(String[] args) }
{ }
Fact obj =new Fact();
int n=5; class RectangleDemo
int res = obj.factorial(n); {
System.out.println("Factorial of " + n + " = " +res); public static void main(String[] args)
} {
} Rectangle obj = new Rectangle();
Output: obj.area(5,4);
C:\>javac FactDemo.java }
}
C:\>java FactDemo
Factorial of 5 = 120 Output:
C:\ >javac RectangleDemo.java
9. Overriding Methods
See this topic in Inheritance.