Java Classes and Objects Overview
Java Classes and Objects Overview
JAVA-UNIT-2
[Link] Page 1
Java-unit-2
What is an Object?
An object is called an instance of a class.
Defining objects of class data type is known as class instantiation.
Memory is allocated only when objects are created.
Objects are basic run-time entities in an object-oriented system.
Any real world entity is called an object.
Objects are the combination of data and methods.
In the real-world only objects are visible but classes are invisible.
Object = Data + Methods
Example: John is an object representing a class called Person.
We can see the object called John but we cannot see the class called Person.
2. 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:
Example:
[Link] Page 2
Java-unit-2
Example:
Farm myFarm
Example: = new Farm();
Program:
class Farm
{
double length;
double width;
double area()
{
return length*width;
}
}
public class FarmExample
{
public static void main (String args[])
{
Farm myFarm = new Farm(); //defining an object of Farm
[Link] = 20.0;
[Link] = 40.0;
[Link]("Area of farm1= " + [Link]());
}
}
***************************************************************************************
[Link] Page 3
Java-unit-2
2. 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 and
- b) non-access modifiers.
Table- gives a description of the various class modifiers.
Examples:
**************************************************************************
[Link] Page 4
Java-unit-2
3. Class Members:
The class members are declared in the body of a class. These may comprise fields (variables in a class). It
contains methods, nested classes, and interfaces. The members of a class comprise the members 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.
2. Class variables ( Static Variables) : These variables are also called 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.
Example Program:
class Sample
{
static int a=20; // static variable
int b=30; // instance variable
public static void main(String[] args)
{
int c=10;
Sample obj = new Sample();
[Link](c);
[Link](Sample.a); // static variable should be accessed with class name
[Link](obj.b); // instance variable is accessed with object
}
}
C:\>javac [Link]
C:\>java Sample
Output:
10
20
30
***************************************************************************************
[Link] Page 5
Java-unit-2
Example:
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
[Link] = 20.0;
[Link] = 40.0;
[Link]("Area of form1= " + [Link]());
farm2 = farm1; // Object Assignment
[Link]("Area of form2 = " + [Link]());
}
}
Output:
C:\>javac [Link]
C:\>java FarmExel
Area of form1= 800.0
Area of form2 = 800.0
***************************************************************************************
6 Q&7Q) Access Control for Class Members (or) Accessing Private Members of Class
In Java, There are four access specifiers are permitted:
• public
• protected
• private
• default
Syntax:
Access_specifier type identifier;
Default :
If a variable is set to default, it will be accessible to the classes which are defined in the same package. Any
method in any class which is defined in the same package can access the variable via Inheritance or Direct
access.
Public
When a variable is set to public it can be accessible from any class available in the Java world. Any method
in any class can access the given method via Inheritance or Direct access depending on class level access.
[Link] Page 6
Java-unit-2
Private
A variable if defined private will be accessible only from within the class it is defined. Such variables are
not accessible from outside the defined class, not even its subclass .
Protected
If a variable is set to protected inside a class, it will be accessible from its sub classes defined in the same or
different package only via Inheritance.
Note: The only difference between protected and default is that protected access modifiers respect class
subclass relation while default does not.
Example:
class Test
{
int a; //default access
public int b; // public access
private int c; // private access
int show(int x) //methods to access c
{
c=x;
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test();
ob.a=1000;
ob.b=2000;
int e=4000;
[Link]("a="+ob.a);
[Link]("b="+ob.b);
[Link]("c="+[Link](3000));
[Link]("e="+e);
}
}
***************************************************************************************
[Link] Page 7
Java-unit-2
[Link] Page 8
Java-unit-2
[Link] Page 9
Java-unit-2
a) Member inner class: A class which is declared within class is called Member inner class.
[Link] Page 10
Java-unit-2
• These classes can refer to local variables or parameters, which are declared final
• These are not visible outside the block in which they are declared and hence, the
access modifiers such as public, private, or protected do not apply to local classes.
Example:
[Link] Page 11
Java-unit-2
class LocalClassDemo
{
public static void main (String args[])
{
class Local // Local class defined
{
int x;
Local(int a)
{
x =a;
}
void display()
{
[Link]("x = "+ x);
}
}
[Link] Page 12
Java-unit-2
{
void inner_display()
{
[Link]("x+y = "+add());
}
}
}
class StaticNestedClass
{
public static void main (String args[])
{
Outer obj =new Outer(10,20);
obj.outer_display();
}
}
Output: C:\>javac [Link]
C:\>java StaticNestedClass
x+y = 30
***************************************************************************************
{
int a,b;
void setValues(int a, int b)
{
this.a = a;
this.b = b;
}
void add()
{
[Link]("Sum = "+(a+b));
}
}
class ThisKeyword
[Link] Page 13
Java-unit-2
{
public static void main (String args[])
{
[Link] Page 14
Java-unit-2
Output:
C:\>javac [Link]
[Link]: error: cannot inherit from final Aclass B extends A
^
1 error
***************************************************************************************
[Link] Page 15
Java-unit-2
{
int x=10,y=20;
[Link]("Before Swap : x= "+x+ " y="+y);
Swap obj =new Swap();
[Link](x,y);
[Link]();
[Link]();
[Link]("After Swap : x= "+x+ " y="+y);
}
}
Output:
C:\>javac [Link]
C:\>java CallByValue
Before Swap : x= 10 y=20
In Swap Class: a= 20 b= 10
After Swap : x= 10 y=20
b).Call by reference:
In call by reference the object will be passed to the method as an argument. At that time the actual
and formal arguments are same.
Example:
class Swap
{
int a,b;
void setValues(Swap obj1)
{
a = obj1.a;
b = obj1.b;
}
void swapping()
{
int temp;
temp =a;
a=b;
b=temp;
}
void display()
{
[Link]("In Swap Class: a= "+a+" b= "+b);
}
}
class CallByReference
{
public static void main (String args[])
{
Swap obj =new Swap();
obj.a=10;
obj.b=20;
[Link]("Before Swap : obj.a = "+ obj.a+" obj.b="+ obj.b);
[Link](obj); // call by reference
[Link] Page 16
Java-unit-2
[Link]();
[Link]();
[Link]("After Swap: obj.a = "+ obj.a+ " obj.b="+ obj.b);
}
}
Output:
C:\>javac [Link]
C:\>java CallByReference
Before Swap : obj.a = 10 obj.b=20
In Swap Class: a= 20 b= 10
After Swap : obj.a = 20 obj.b=10
***************************************************************************************
II. Methods
1. Introduction
• A method in Java represents an action on data or behaviour of an object. The methods are called functions or
procedures.
• In Java, a method must be defined inside a class and an interface.
• An interface represents an encapsulation of constants, classes, interfaces, and one or more abstract methods
that are implemented by a class.
• A method cannot be defined inside another method, but it can be defined inside a local class.
2. Defining Methods
A method definition comprises two components:
[Link] that includes modifier, type, identifier, or name of method and a list parameters.
• The parameter list is placed in a pair of parentheses.
2. Body that is placed in braces ({ }) and
• It consists of declarations and executable statement and other expressions.
Method definition:
Modifier return_type method_name (datatype Parameter_Name,…)
{
/*Statements --
Body of the method*/
}
Example:
void show(int x, int y) //method with two arguments and without return type
{
a = x;
b = y;
}
[Link] Page 17
Java-unit-2
Example Program:
class Add
{
int a,b;
void show(int x, int y) // method with arguments and without return type
{
a = x;
b = y;
[Link]("a="+a+",b="+b);
}
void display() //method without arguments and without return type
{
[Link]("Welcome to Methods Concepts");
}
int add(int x, int y) // method with arguments and return type
{
int c=x+y;
return c;
}
}
class MethodDemo
{
public static void main (String args[])
{
Add obj= new Add();
[Link](10,20);
[Link]();
[Link]("Sum ="+[Link](10,20));
}
}
Ouyput:
C:\ >javac [Link]
C:\ >java MethodDemo
a=10,b=20
Welcome to Methods Concepts
Sum =30
[Link] Page 18
Java-unit-2
************************************************************************************
3. Overloaded Methods or Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
[Link] Page 19
Java-unit-2
class OverloadDemo
{
void test()
{
[Link]("No parameters");
}
void test(int a) // Overload test for one integer parameter.
{
[Link]("a: " + a);
}
void test(int a, int b) // Overload test for two integer parameters.
{
[Link]("a*b=" +(a*b));
}
void test(int a, int b,int c) // Overload test for two integer parameters.
{
[Link]("a+b+c=" +( a+b+c));
}
void test(double a, double b) // Overload test for two integer parameters.
{
[Link]("a/b=" +(a/b));
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
[Link]();
[Link](10);
[Link](10, 20);
[Link](5,3,2);
[Link](10.0,5.0);
}
}
****************************************************************************************************************
4. Overloaded Constructor Methods
A constructor method is automatically called whenever a new object of the class is constructed. It creates
and initializes the Object.
A constructor method has the same name as the name of class to which it belongs. It has no type and it
does not return any value. It only initializes the object.
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 parameters, it will pick up default
values when these are not specified in the object definition.
Example:
class AddDemo
{
int a,b;
AddDemo() // Constructor without arguments
{
a=10;
b=20;
[Link] Page 20
Java-unit-2
}
AddDemo(int x, int y) // Constructor Overloading with arguments
{
a = x;
b = y;
}
void add() // method without arguments
{
[Link]("a = " + a + ", b = "+ b+ ": Sum = "+ (a+b) );
}
}
class ConstructorOverload
{
public static void main (String args[])
{
AddDemo obj1= new AddDemo(); //calling constructor without arguments
[Link]();
AddDemo obj2= new AddDemo(150,60); //calling constructor with arguments
[Link]();
}
}
Output:
C:\>javac [Link]
C:\>java ConstructorOverload
a = 10, b = 20: Sum = 30
a = 150, b = 60: Sum = 210
Example:
class AddDemo
{
int a,b;
[Link] Page 21
Java-unit-2
obj1.b=200;
[Link](obj1);
}
}
Output:
C:\>javac Object AsParamet [Link]
C:\>java Object AsParamet er
Addit ion= 300
6. Access Control
Java supports access control at the class level and at the level of class members. At the class level,
the following two categories are generally used:
default case no modifier applied : In the default case, when no access specifier isapplied,
the class can be accessed by other classes only in the same package
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
iii. public
i v. default case-no modifier specified
i). private : The private members can only be accessed by the other members (methods) of the same class. No other
code outside the class can access them.
Ex: private int x;
private int getx()
{
return x;
}
ii). protected : The protected members can accessed by own class and derived class only.
protected int x;
protected int getx()
{
return x;
}
iii). public : The public members can accessed by all the classes.
Ex: public int x;
public int getx()
{
return x;
}
[Link] Page 22
Java-unit-2
iv). default case ( no modifier specified ): The default members can accessed by all the classes within the package
only.
int x;
int getx()
{
return x;
}
Example Program-2: [Link]-6 & 7(6 Q&7Q) Access Control for Class Members (or)
Accessing Private Members of Class)
**************************************************************************
7. Recursive Methods
A Method which is calling itself is called as Recursive Method.
Syntax:
returntype methodname()
{
//code to be executed
methodname(); //calling same method
}
Example-1: Recursive method to find factorial of a given number.
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 x= [Link](n);
[Link]("Factorial of " + n + " = " +x);
}
}
Output:
C:\>javac [Link]
C:\>java FactDemo
Factorial of 5 = 120
[Link] Page 23
Java-unit-2
[Link] Page 24
Java-unit-2
Output:
C:\ >javac Ar i t h m a t i c [Link]
C:\ >java Ar it h m a t i c Demo
A =5, B= 4
Addition=9
Multiplication= = 20
************************************************************
9. Overriding Methods
See this topic in Inheritance.
[Link] Page 25