0% found this document useful (0 votes)
49 views

UNIT-2 Notes

Classes and Objects
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

UNIT-2 Notes

Classes and Objects
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT-2

Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
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, Class Objects as Parameters in Methods, Access Control, Recursive Methods,
Nesting of Methods, Overriding Methods, Attributes Final and Static.

Concept-1 Classes and Objects: Introduction


Classes:
 In object-oriented programming technique, we design a program using objects and classes.
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.
 It is a logical entity. It can't be physical.
 Classes are user-defined data type.
 Very simple class may contain only code and only data (Data member & methods).
 A class is declared by use of the class keyword.
 A class in Java can contain: 1. Fields 2. Methods 3. Constructors 4. Blocks 5. Nested
class and interface.
 The data and variables, defined within a class are called instance variables.
 Instance variable doesn't get memory at compile time.
 It gets memory at runtime when an object or instance is created.
 The code is contained within methods, the methods and variables defined within a class are
called members of the class.
Objects:
 An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
 An object is a real-world entity. An object is a runtime entity.
 An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc.
 The object is an instance of a class.
An object has three characteristics
State: Represents the data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
Concept-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 class 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 with
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.
 The class names should be simple and descriptive.
 Class names are nouns.
 For example, it could include names such as vehicles, books, and symbols.
 Acronyms and abbreviations should be avoided.
Class Modifier
 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.
Example of class Declarations
1. A class without a modifier is declared with keyword class followed by name/identifier of
class, and name is followed by a pair of braces { }.
package pack1;
class Myclass{
/* class body */
}
A class must belong to a package. If a programming does not specify a package, the class is
placed in the default package generated by a compiler.
2. A class with modifier is declared as follows
package pack1;
public class Myclass{
/* class body */
}
This class is visible to all other classes in any package.
3. The modifier class with private and protected is used only for nested class.
package pack1;
class X{
Statements;
private class Myclass
{ // Class body
}
}
A private class is declared inside another class. Therefore, this class is visible to other member
of the enveloping class in which it is declared. For all other classes, this class is not visible.
4. Class with the final modifier are declared as follows
package pack1;
final class Myclass{
// Class body
}
A class with the modifier final cannot be extended that is cannot have subclasses but it can
have a super class.
5. Class with the abstract modifier are declared as follows
package pack1;
abstract class Myclass{
abstract void display();
}
A class declared abstract must have one or more abstract methods as its members that is
methods without a body; it is only the header of a method followed by semicolon.
Concept-3 Class Members
 The class members are declared in the body of a class.
 The class member may contain fields (variables in a class), methods, nested classes, and
interfaces.
 The member of a class contains 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.
There are two type of variable
1.Non Static variables: These include instance and local variables and vary in scope and value.
(a) Instance variables: These variables are individual to an object and an object keeps a copy
of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables (Static Variables): These variables are also contains as static keyword. The
values of these variables are common to all the objects of the class.
Program:-
Concept-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;
For Example A Class defined as
public class Farm{
int length;
int width;
}
An Object of class Farm may be declared as null
Farm myFarm;
 Here, the variable myFarm simply refers to an object of Farm class whose value at present is
null;
 The new operator creates a new object or an instance of a class. With this, the objects are
created.
 The memory is allocated dynamically in the heap at runtime of the program.
Object_name = new className();

Name of the object Class name or constructor name

 The object is created as follows

 Here, myFarm is a variable of the type Farm. Each object of the Farm class has allocated
memory that can hold the values of instance variables length and width.
 Definition/Creation of object

Program:-

Output:-

Area of myFarm = 800.0


Concept-5 Assigning One Object to Another
 When one object of a class provides a reference to another object of the same class, the first
object can access the second object’s data and methods.
 Java provides the facility to assign one object to another object all the properties of
old_object will be copied to new object.
Syntax: new_Object = old_object;
 The Following is the example as follows
farm2=farm1;
Here farm2 and farm1 are the objects of the same class Farm.
Program:-

Output:-

Area of form1= 800.0


Area of form2 = 800.0
Concept-6 Access Control for Class Members
 An access modifier in java specifies accessibility (scope) of instance variables, methods,
classes, constructor etc.
 In Java, There are three access specifiers are permitted:
1. public 2. protected 3. private 4. default or No modifier
private: private has scope within the class only
public: public has scope useful to every where
protected: protected has scope within the package and, child class of same package and child
class of other package
Default or No modifier: if you don’t use any modifier it is treated as default it is accessible
only within the package.
The coding with access specifiers for variables is illustrated as
access_specifier type identifier;
Examples: int n; //No access specifier
public int m; //public access.
protected int k; //protected
private int p; //private – access only to class members
Concept-7 Accessing Private Members of Class
 Private members of a class, whether they are instance variables or methods, can only be
accessed by other members of the same class.
 Any outside code cannot directly access them because they are private. However, interface
public method members may be defined to access the private members.
 The code other than class members can access the interface public members that pass on the
values.
Program:-
Output:-

Concept-8 Constructor Methods for Class


 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new keyword, at least one constructor is called.
 A constructor is a block of codes similar to the method. It is called when an instance of the
class is created.
 At the time of calling constructor, memory for the object is allocated in the memory.
 It calls a default constructor if there is no constructor available in the class.
 In such case, Java compiler provides a default constructor by default.
Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no return type
3. A Java constructor cannot be abstract, static, final, and synchronized
4. Constructor cannot be inherited
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor
 A constructor is called "Default Constructor" when it doesn't have any parameter.
 The default constructor provided by java compiler, is a no-argument constructor with empty
body.
 The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
 If there is no constructor in a class, compiler automatically creates a default constructor.
Syntax of default constructor

Program:-
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.
 Arguments can be passed to the constructor in order to initialize the instance variable of an
object.
 It has a mechanism for automatically initializing the values for objects as soon as the object
is created. This mechanism is called as constructors.
Program:-
Concept-9 Final Class and Methods
Final Class
 A class that is declared with the final keyword is known as the final class.
 A final class can’t be inherited by subclasses.
 By use of the final class, we can restrict the inheritance of class.
 In java, all the wrapper classes are final class like String, Integer, etc.
 If we try to inherit a final class, then the compiler throws an error at compilation time.
 We can create a class as a final class only if it is complete in nature it means it must not be
an abstract class.
Syntax:
accessModifier final class className
{
// Body of class
}
Program:-
Final Method
 We can declare a method as final, once you declare a method final it cannot be overridden.
So, you cannot modify a final method from a sub class.
 The main intention of making a method final would be that the content of the method should
not be changed by any outsider.
Syntax:-
final accessmodifier datatype methodname(Parameter….){
// Method body
}
Program:-
Concept-10 Passing Arguments by Value and by Reference
Call by Value:
 Call by Value means calling a method with a parameter as value. Through this, the argument
value is passed to the parameter.
 In call by value, the modification done to the parameter passed does not reflect in the caller's
function.
 Any modification done in called function will not affect the original value. i.e., actual and
formal parameters are different
Program: Output:-

Call by Reference
 Call by Reference means calling a method with a parameter as a reference. Through this, the
argument reference is passed to the parameter.
 In call by reference the object will be passed to the method as an argument.
 In the call by reference, the modifications done to the parameter passed are persistent and
changes are reflected in the caller's function.
 That means any occurs in actual arguments will be reflected in the formal arguments.
Program: Output:-

Concept-11 Keyword this


 this keyword in Java is a reference variable that refers to the current object of a method or a
constructor.
 this keyword in Java is to remove the confusion between class variable and parameters that
have same names.
Following are various uses of ‘this’ keyword in Java
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
Program:
Output:-

Concept-12 Nested Classes


 The Java programming language allows you to define a class within another class. Such a
class is called a nested class.
 Non-static nested classes (inner classes) have access to other members of the enclosing class,
even if they are declared private.
 We need to take support of outer class to access inner class.
Program:
Concept-11 Methods: Introduction & Defining Methods
Methods in JAVA
 Method is a way to perform some task.
 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.
 The method in Java is a collection of instructions that performs a specific task.
 It provides the reusability of code.
 Can also easily modify code using methods.
 What is a method in Java?
Return type of methods, method declaration, and how to call a method in Java
 Write a method once and use it many times. Do not require to write code again and again.
 It also provides the easy modification and readability of code.
 The method is executed only when we call or invoke it.
 In Java, a method must be defined inside a class and an interface.
 The most important method in Java is the main() method.
 The main() is the starting point for JVM to start execution of a Java program.
 Without the main() method, JVM will not execute the program.
Method Declaration
 The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments (Parameter List).
 It has six components that are known as method Declaration.
Method Signature
 Every method has a method signature. It is a part of the method declaration. It includes the
method name and parameter list.
a) 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 Program.
Program
Private: When
hen 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.
b) Return Type: Return type is a data type
type that the method returns. It may have a primitive
data type, etc. If the method does not return anything, we use void keyword.
c) Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method.
If we are creating a method for subtraction of two numbers, the method name must be
subtraction(). A method is invoked by its name.
d) 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.
c) 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.
Naming a Method
 While defining a method, the method name must be a verb and start with a lowercase letter.
 If the method name has more than two words, the first name must be a verb followed by
adjective or noun.
 In the multi-word method name, the first letter of each word must be in uppercase except the
first word. For
Example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Program:-
Concept-12 Overloaded Methods
 If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
 Method Overloading is one way of achieving polymorphism in JAVA.
 If we have to perform only one operation, having same name of the methods but different in
parameters is increases the readability of the program.
Advantage of method overloading
 Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
 Method Overloading is not possible by changing the return type of the method only.
Method Overloading Changing no. of arguments
 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.
 We are creating static methods so that we don't need to create instance for calling methods.
Program:-

Method overloading changing data type of arguments


 We have created two methods that differ in data type.
 The first add method receives two integer arguments and second add method receives two
double arguments.
Program:-

Concept-13 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.
 Constructor overloading in Java is a technique that enables a single class to have more
than one constructor that varies by the list of arguments passed.
 The constructor overloading enables the accomplishment of static polymorphism.
 Each overloaded constructor performs various tasks for specified purposes.
Program:-

Output:-
Concept-14 Class Objects as Parameters in Methods
 Object as an argument is use to establish communication between two or more objects
of same class.
 Objects can be passed as parameters to the Methods just like primitive data types.
 It is called as Call by Reference.
 When a primitive type is passed to a method, it is done by use of call-by-value.
 Objects are implicitly passed by use of call-by-reference.
 This means when we pass primitive data types to method it will pass only values to
function parameters so any change made in parameter will not affect the value of
actual parameters.
Program:-

Output:-
Concept-15 Recursive Methods
 Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Example:-

Program:-

Output:-
Concept-16 Nesting of Methods
 A method of a class can be called only by an object of that class using the dot operator
(.) So, there is an exception to this.
 A method can be called by using only its name by another method of the same
class that is called Nesting of Method.
Program:-
Concept-17 Overriding Methods
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
 In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
1. Method overriding is used for runtime polymorphism

2. Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Program:-

Output:-
Important Question
1. Explain the concept of call by value and call by reference with an example.
2. Explain the concept of Nesting of Methods with an example.
3. Discuss the significance of overriding methods with a program.
4. Write a Java method to find the minimum values in given two values
5. Explain the need for recursive methods in Java with an example.
6. Explain the difference between method overloading and constructor overloading with
examples.
7. What access modifiers may be used with in a class? How do you access a methods
declared private in a class?
8. What is the constructor methods in a Java explain with an example program?
9. Write a short note on this keyword in Java?
10. Explain about final class and final method in Java?
11. What is a class and object? How to declared and class and object in Java with an
example program?
12. Explain about Assigning One Object to Another object in Java with an example?
13. Explain about class member of class in Java?

You might also like