Unit - 4 - Objects and Classes - OOP Notes
Unit - 4 - Objects and Classes - OOP Notes
Object oriented programming provides data Procedural programming does not have any
hiding so it is more secure. proper way for hiding data so it is less secure.
Object oriented programming have access There is no access specifier in procedural
specifiers like private, public, protected,default. programming.
In OOP, there is a concept of function Overloading is not possible in procedural
overloading and operator overloading. programming.
It is appropriate for complex problems. It is not appropriate for complex problems.
The examples of object-oriented programming Examples of Procedural programming include
are-.NET, C#, Python, Java, VB.NET, and C++. C, Fortran, Pascal, and VB.
2. Explain types of variables and scope of instance, class and local variable with the help of
example
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is
declared. i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined
scope.
1
Unit-4: Objects and Classes
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor, or block.
As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be used.
Initialization of Instance Variable is not mandatory. Its default value depends on
data type.
Instance Variable can be accessed only by creating objects.
3. Static Variables
Static variables are also known as Class variables.
These variables are declared similarly as instance variables. The difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of Static Variables is not mandatory.
If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message, which won’t halt the program. The
compiler will replace the object name with the class name automatically.
If we access the static variable without the class name, the compiler will
automatically append the class name.
Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of the instance variable.
In the case of static, changes will be reflected in other objects as static variables are
common to all objects of a class.
2
Unit-4: Objects and Classes
EX-2
class Student {
String name; // name has the default value null
int age; // age has the default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // gender has default value '\u0000'
}
Class is a template, blueprint, or contract that defines what an object’s data fields and methods
will be.
A class defines the properties and behaviors for objects.
An object is an instance of a class.
We can create many instances of a class.
An object represents an entity in the real world that can be distinctly identified.
For example, a student.
An object has a unique identity, state, and behavior.
o The state of an object (also known as its properties or attributes) is represented by data
fields with their current values.
A circle object, for example, has a data field radius.
o The behavior of an object (also known as its actions) is defined by methods.
3
Unit-4: Objects and Classes
An object’s data and methods can be accessed through the dot (.) operator via the object’s reference
variable.
Circle myCircle = new Circle();
The variable myCircle holds a reference to a Circle object new Circle().
Accessing an Object’s Data and Methods
After an object is created, its data can be accessed and its methods can be invoked using the dot
operator (.), also known as the object member access operator:
creates a Circle object and invokes its getArea() method to return its area.
An object created in this way is known as an anonymous object.
4
Unit-4: Objects and Classes
6. Define object oriented concepts OR List out and explain three main principles of object-
oriented programming?
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects.
It simplifies software development and maintenance by providing some concepts:
1. Object
Any entity that has state and behaviour is known as an object.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory. A class is a template
or blueprint from which objects are created. So, an object is the instance (result) of a
class.
State: represents the data (value) of an object.
Behaviour: represents the behaviour (functionality) of an object such as deposit,
withdrawal, etc.
2. Class
A class is a group of objects which have common properties.
Collection of objects is called class.
It is a template or blueprint from which objects are created.
It is a logical entity.
It can't be physical.
A class in Java can contain: Field, Method, Constructor, blocks, Nested class…
Syntax to declare a class:
class <class_name>{
Data fields section;
Constructors section;
5
Unit-4: Objects and Classes
methods section;
}
3. Abstraction
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
It focuses on reducing design complexity.
It can be achieved by keeping main() method implementation to test utility class in
separate class
Another way, it shows only essential things to the user and hides the internal details.
In Java, we use abstract class and interface to achieve abstraction.
4. Encapsulation
Encapsulation is used to hide the values or state of an bject inside a class, preventing
direct access to them by clients in a way that could expose hidden implementation
details or violate any restriction on an object.
Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of
the class private.
Now we can use setter and getter methods to set and get the data in it.
5. Inheritance
When one class (subclass) acquires all the properties and behaviours of its parent class
(superclass), it is known as inheritance.
It provides code reusability.
It is used to achieve runtime polymorphism.
6. Polymorphism:
Polymorphism in Java is a concept by which we can perform a single action in
different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
If one task is performed in different ways, it is known as polymorphism.
A real-life example of polymorphism, a person at the same time can have different
characteristics. Like a man at the same time is a person and an employee.
In Java, we use method overloading and method overriding to achieve polymorphism.
7. What is the purpose of ‘static’ keyword? Write a program to demonstrate the use of static
members of the class OR Explain static variable and static method with example.
The static keyword in Java is used for memory management mainly.
The static keyword belongs to the class than an instance of the class.
‘static’ keyword is used for variable, method, block and nested class(inner class)
A static variable, also known as class variable is shared by all objects of the class.
6
Unit-4: Objects and Classes
Static variables store values for the variables in a common memory location.
A static method can be called without creating an instance of the class.
A static method cannot access instance members of the class directly.
For example, suppose that you create the following objects:
Circle circle1 = new Circle();
Circle circle2 = new Circle(5);
The radius in circle1 is independent of the radius in circle2 and is stored in a different memory
location. Changes made to circle1’s radius do not affect circle2’s radius, and vice versa.
To declare a static variable or define a static method, put the modifier static in the
variable or method declaration.
Constants in a class are shared by all objects of the class. Thus, constants should be
declared as final static. For example, the constant PI in the Math class is defined as:
Example of static variable and method: Program to create the new circle class, named Circle
having a static method getObjects() that keeps track of the number of objects created for the
mentioned class.
class Circle {
double radius;
static int Objects = 0; //static variable-shareb by all objects
7
Unit-4: Objects and Classes
Circle() {
radius = 1;
Objects++;
}
NOTE:
Use ClassName.methodName(arguments) to invoke a static method and
ClassName.staticVariable to access a static variable. This improves readability, because this
makes the static method and data easy to spot.
static method is used to manipulate static variable
8
Unit-4: Objects and Classes
Example
import static java.lang.Math.*;
public class Sample{
public static void main(String args[]){
System.out.println(sqrt(25));
}
}
Output
5.0
A constructor must have same name as that of the A method name can not be same as class name.
class.
A constructor cannot be inherited by a subclass. A method is inherited by a subclass.
9
Unit-4: Objects and Classes
}
public static void main(String args[]) {
JavaTester tester = new JavaTester(); //constructor
tester.init(); //method
}
}
Output
Constructor invoked.
Method invoked.
10. What is a constructor in JAVA? How many types of constructors are there in JAVA?
Explain with examples.
In Java, 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 the constructor, memory for the object is allocated in the
memory.
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. It calls
a default constructor if there is no explicit constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
10
Unit-4: Objects and Classes
{
//calling a default constructor
Bike b=new Bike();
}
}
Output : Bike is created
11. What do you mean by Overloading? Explain constructor overloading with suitable
example.
Constructor overloading in Java refers to the use of more than one constructor in an instance class.
However, each overloaded constructor must have different signatures.
Each constructor is differentiated by the compiler by the number of parameters in the list and their
types.
11
Unit-4: Objects and Classes
Constructors can be public, private, protected or default (no access modifier at all).
12
Unit-4: Objects and Classes
Making something private doesn't mean nobody can access it. It just means that nobody outside
the class can access it. So private constructor is useful too.
One of the use of private constructor is to serve singleton classes. A singleton class is one which
limits the number of objects creation to one. Using private constructor we can ensure that no more
than one object can be created at a time.
14. Using classes from the java library OR Explain Random and Date class with the help of a
program.
The Java API contains a rich set of classes for developing Java programs.
The Date Class
A Date object represents a specific date and time.
13
Unit-4: Objects and Classes
For example, the following code creates two Random objects with the same seed 3.
Write a program to create a Point2D object for a point with the specified x- and y-coordinates,
use the distance method to compute the distance from this point to another point, and use the
toString() method to return a string representation of the point.
import java.util.Scanner;
import javafx.geometry.Point2D;
14
Unit-4: Objects and Classes
15
Unit-4: Objects and Classes
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
class A{
private int data=50;
private void msg()
{
System.out.println("Hello java");
}
}
2. Protected : The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
//save by A.java
package pack;
public class A{
protected void msg()
{
System.out.println("Hello Java");
}
}
//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 Java
16
Unit-4: Objects and Classes
3. Public : The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello Java");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello Java
4. Default: When no access modifier is specified for a class, method, or data member – It is
said to be having the default access modifier by default.
The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package
(package private).
In this example, we will create two packages and the classes in the packages will be
having the default access modifiers and we will try to access a class from one package
from a class of the second package.
// Java program to illustrate error while using class from different package with default
// modifier
package p2;
import p1.*;
// This class of package p2 is having default access modifier
class Class2
{
public static void main(String args[])
{
// Accessing Class1 from package p1
Class1 obj = new Class1();
obj.display();
}
}
Output:
Compile time error
17
Unit-4: Objects and Classes
Making data fields private protects data and makes the class easy to maintain.
To prevent direct modifications of data fields, you should declare the data fields private,
using the private modifier. This is known as data field encapsulation.
Encapsulation is useful in hiding the data(instance variables) of a class from an illegal
direct access.
To make a private data field accessible, provide a getter method to return its value. To
enable a private
data field to be updated, provide a setter method to set a new value. A getter method is
also referred to as an accessor and a setter to a mutator.
18
Unit-4: Objects and Classes
Write a program to demonstrate passing an object to a method to check if two objects are
equal or not.
Output:
To initialize circleArray, you can use a for loop like this one:
for (int i = 0; i < circleArray.length; i++) {
circleArray[i] = new Circle();
}
19
Unit-4: Objects and Classes
Note
When an array of objects is created using the new operator, each element in the array is
a reference variable with a default value of null.
JAVA CO OS
12 23 18
20 25 19
13 14 15
You can define immutable classes to create immutable objects. The contents of immutable
objects cannot be changed.
Immutable class means that once an object is created, we cannot change its content. In Java,
all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
We can create our own immutable class as well.
20
Unit-4: Objects and Classes
If a class contains only private data fields and no setter methods, is the class
immutable?
Not necessarily. To be immutable, the class must also contain no getter methods that would
return a reference to a mutable data field object.
A mutable object can be changed after it's created, and an immutable object can't.
Any time you change a string (e.g.: tacking on an extra character, making it lowercase,
swapping two characters), you're actually creating a new and separate copy
Immutability is mainly used for thread-safety and hashing techniques.
21
Unit-4: Objects and Classes
22
Unit-4: Objects and Classes
NOTE:
Java requires that the this(arg-list) statement appear first in the constructor before any other
executable statements.
If a class has multiple constructors, it is better to implement them using this(arg-list) as much
as possible. In general, a constructor with no or fewer arguments can invoke a constructor
with more arguments using this(arg-list). This syntax often simplifies coding and makes the
class easier to read and to maintain.
23