Wa0008

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Object Oriented Programming[214444]

Second Year Information Technology (2019 Course)


Unit 2 : Classes, Objects, & Methods
Syllabus:-
Class : Creating a Class, Visibility/Access Modifiers, Encapsulation, Methods: Adding a Method to Class,
Returning a Value, Adding a Method that takes Parameters, The “this” Keyword, Method Overloading,
Object Creation, Using Object as a Parameters, Returning Object, Array of Objects, Memory Allocation:
“new”, Memory Recovery: “delete”, Static Data Members, Static Methods, Forward Declaration, Class as
Abstract Data Types (ADTs), Classes as Objects.

Unit Objectives
On completion of the unit students will be able to:
1. To understand concepts of classes, methods and objects.
2.To understand different types of methods
3.To understand fundamentals of objects
4. To understand fundamentals of memory allocation

Unit Outcomes:
1. To learn need of classes, objects and methods .

Texts Books:
T1) An Introduction to Object Oriented Programming (3rd Ed), by Timothy A. Budd, published by Addison-
Wesley,2002
T2) E. Balaguruswamy, “Object Oriented Programming Using C++ and Java”, Tata McGrawHill

Outcome Satisfied: PEOs: 1 PSOs:2 POs: a,c,e COs:1


Outline
Sr. No. Topic Name Reference Book

1 Class : Creating a Class, Visibility/Access Modifiers, T2(Page No. 95, 339)


Encapsulation,

2 Methods: Adding a Method to Class, Returning a Value, T2(Page No.99,340)


Adding a Method That Takes Parameters,

3 The “this” Keyword, Method Overloading, Object Creation, T2(Page No.248,347)


Memory Allocation: “new”, Memory Recovery: “delete”,

4 Using Object as a Parameters, Returning Object, T2(Page No.117)

5 Array of Objects, Static Data Members, Static Methods, T2(Page No.109-114)

6 Forward Declaration, Class as Abstract Data Types (ADTs), T2(Page No.110-112,348)


Classes as Objects
Case study
Creating Class
• A class is a blueprint or prototype that defines the variables and
the methods (functions) common to all objects of a certain kind.

• Objects (data and functions) are members of user-defined types


called classes.

• To create a class, use the keyword class:

public class Student


{

}//End of Student Class


Visibility/Access Modifier
• An accessmodifier is used to set the access level for classes, attributes, methods and
constructors.
• For classes, we can use either public or default access modifier

• Public
– The class is accessible by any other class

public class Student{

}//End of Student Class


• Default
– The class is only accessible by classes in the same package. This is used when you don't
specify a modifier.

class Student{

}//End of Student Class


Visibility/Access Modifier
• For attributes, methods and constructors, you can use the one of the following
Public
•The code is accessible for all classes
public class Person {
public String fname = "John";
public String lname = "Doe";
public String email = "john@doe.com";
public int age = 24;
}
class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Age: " +myObj.age); Output:
} Name: John Doe
} Email: john@doe.com
Age: 24
Visibility/Access Modifier
Private
•The code is only accessible within the declared class
public class Person
{
private String fname = "John";
private String lname = "Doe";
private String email = "john@doe.com";
private int age = 24;
public static void main(String[] args)
{
Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Age: " +myObj.age); Output:

} Name: John Doe


Email: john@doe.com
} Age: 24
Visibility/Access Modifier
Default
• The code is only accessible in the same package. This is used when you don't
specify a modifier.
class Person {
String fname = "John";
String lname = "Doe";
String email = "john@doe.com";
int age = 24;
public static void main(String[] args) {
Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Age: " +myObj.age);
}
Output:
} Name: John Doe
Email: john@doe.com
Age: 24
Visibility/Access Modifier
Protected
•The code is accessible in the same package and subclasses.
class Person {
protected String fname = "John";
protected String lname = "Doe";
protected String email = "john@doe.com";
protected int age = 24;
}
class Student extends Person {
private int graduationYear = 2018;
public static void main(String[] args) {
Student myObj = new Student();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);

System.out.println("Age: " +myObj.age); Output:


System.out.println("Graduation Year: " + myObj.graduationYear); Name: JohnDoe
Email: john@doe.com
} Age: 24
Graduation Year : 2018
}
Encapsulation

• The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users.
• We can achieve encapsulation in Java by:
– Declaring the variables of a class as private.
– Providing public setter and getter methods to modify and view the variables
values.
•Let us look at the code below to get a better understanding of encapsulation:
public class Person { //class 1
private String name; / / private = restricted access
/ / Getter
public String getName() {
return name;
}
/ / Setter
public void setName(String newName)
{ this.name = newName;
}
}
Encapsulation

• However, as the name variable is declared as private, we cannot access it from


outside the class

public class MyClass { //class 2


public static void main(String[] args)
{
Person myObj = new Person();
myObj.name = "John"; / / error
System.out.println(myObj.name); / / error
}
}

However, as we try to access a private variable, we get an error.


Encapsulation

• Instead, we use the getName() and setName() methods to acccess and update
the variable:

public class MyClass


{
public static void main(String[] args)
{
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John“
System.out.println(myObj.getName());
}
}

• Output: "John"
Encapsulation
Why Encapsulation?

• Better control of class attributes and methods

• Class attributes can be made read-only (if you only use the get method),
or write-only (if you only use the set method)

• Flexible: the programmer can change one part of the code without affecting
other parts

• Increased security of data


Adding a Method to Class
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as
functions.
• Why use methods? Toreuse code: define the code once, and use it many
times.
• Create a method inside MyClass:
public class MyClass {
static void myMethod() {
/ / code to be executed
}
}
• myMethod() is the name of the method
• static means that the method belongs to the MyClass class and not an
object of the MyClassclass.
• void means that this method does not have a return value.
Calling a Method
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}

• Output: "I just got executed!"


Returning a Value

• If you want the method to return a value, you can use a primitive data type
(such as int, char, etc.) instead of void, and use the return keyword inside
the method.
• The void keyword indicates that the method should not return a value

public class MyClass {


static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}

• Output: 8
Adding a Method that Takes Parameters

• Information can be passed to methods as parameter. Parameters act as


variables inside the method.
• Parameters are specified after the method name, inside the parentheses.
• You can add as many parameters as you want, just separate them with a
comma.
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + “ Institutes");
}
public static void main(String[] args) {
myMethod(“Sinhgad");
}
}

• Output: Sinhgad Institutes


‘this’ Keyword
• The this keyword refers to the current object in a method or constructor.
• The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the samename
public class MyClass {
int x;
/ / Constructor with a parameter
public MyClass(int x) {
this.x = x;
}
/ / Call the constructor
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println("Value of x = " +myObj.x);
}
}
If you omit the keyword in the example above, the output would be "0" instead
of "5".
‘this’ Keyword
‘this’ keyword can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

‘this’KeywordVideo
Method Overloading

• In Method Overloading, multiple methods can have the same name with
different parameters
• Example:
– int myMethod(int x)
– float myMethod(float x)
– double myMethod(double x, double y)
• we have to perform only one operation, having same name of the methods
increases the readability of the program.
• Method overloading increases the readability of the program.
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Method Overloading
• Method Overloading by changing no. of arguments

class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method Overloading
• Method Overloading by changing data type of arguments

class Adder{
static int add(int a,int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11.2,11.3));
}}
Method Overloading
• Why Method Overloading is not possible by changing the return type of
method only?
class Adder{
static int add(int a,int b){
return a+b;
}
static double add(int a, int b){
return a+b;
}}
class TestOverloading{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
}}
In java, method overloading is not possible by changing the return type of the
method only because of ambiguity
Object Creation
• In Java, an object is created from a class
• Tocreate an object of Class, specify the class name, followed by the object
name, and use the keyword new
public class MyClass {
int x = 5;
public static void main(String[] args) { MyClass
myObj = new MyClass();
System.out.println(myObj.x);
}
}

• You can create multiple objects of one class


• MyClass myObj1 = new MyClass(); / / Object 1
• MyClass myObj2 = new MyClass(); / / Object 2
Memory Allocation : ’new’
• The new keyword creates new objects.
• C++allows us to allocate the memory of a variable or an array in run time.
This is known as dynamic memory allocation.
• In Java, all objects are dynamically allocated on Heap.
• This is different from C++where objects can be allocated memory either
on Stack or on Heap.
• In C++, when we allocate the object using ‘new’ keyword, the object is
allocated on Heap, otherwise on Stack if not global or static.
• In Java, when we only declare a variable of a class type, only a reference is
created (memory is not allocated for the object).
• Toallocate memory to an object, we must use ‘new’. So the object is
always allocated memory on heap
• syntax for using the new operator is
pointerVariable = new dataType;
Memory Allocation : ’new’
public class MyClass {
int x = 5;
public static void main(String[] args) {
MyClass myObj ;
myObj = new MyClass();
System.out.println(myObj.x);
}
}
Memory Recovery : ’delete’

• In other programming languages such as Java and Python, the compiler


automatically manages the memories allocated to variables. But this is not
the case in C++.
• In C++, we need to deallocate the dynamically allocated memory manually
after we have no use for the variable.
• We can allocate and then deallocate memory dynamically using the new
and delete operators respectively.
• Once we no longer need to use a variable that we have declared
dynamically, we can deallocate the memory occupied by the variable.
• For this, the delete operator is used. It returns the memory to the
operating system. This is known as memory deallocation.
• The syntax for ‘delete’ operator is
delete pointerVariable;
Memory Recovery : ’delete’

/ / declare an int pointer


int* pointVar;
/ / dynamically allocate memory for an int variable
pointVar = new int;
/ / assign value to the variable memory
*pointVar = 45;
/ / print the value stored in memory
cout << *pointVar; / / Output: 45
/ / deallocate the memory
delete pointVar;

Here, we have dynamically allocated memory for an int variable using the
pointer pointVar.
After printing the contents of pointVar, we deallocated the memory
using delete
Using Object as Parameters
• Object references can be parameters.
• Call by value is used, but now the value is an object reference.
• This reference can be used to access the object and possibly change it.
• When we pass a primitive type to a method, it is passed by value. But when
we pass an object to a method, the situation changes dramatically, because
objects are passed by what is effectively call-by-reference.
• Java does this interesting thing that’s sort of a hybrid between pass-by-
value and pass-by-reference.
• Basically, a parameter cannot be changed by the function, but the function
can ask the parameter to change itself via calling some method within it.
– While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
– This effectively means that objects act as if they are passed to methods by use of call-by-
reference.
– Changes to the object inside the method do reflect in the object used as an argument.
Using Object as Parameters
public class Rectangle { public void set(double l, double w) {
private double length; length = l;
private double width; width = w;
public Rectangle() { }
length = 0.0; public double getLength() {
width = 0.0; return length;
} }
public Rectangle(double l, double cpublic double getWidth() {
w) { return width;
length = l; }
width = w; public double getArea() {
} return length * width;
public void setLength(double l) { }
length = l; public double getPerimeter() {
} return 2 * (length + width);
public void setWidth(double w) { }
width = w;
}
}
Using Object as Parameters
public class PassObjectDemo {
public static void main(String[] args) {
/ / Create an Rectangle object.
Rectangle rect = new Rectangle(10, 20);
/ / Display the object's contents.
System.out.println("Length : " +rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " +rect.getArea());
/ / Passthe object to the ChangeRectangle method.
changeRectangle(rect);
/ / Display the object's contents again.
System.out.println();
System.out.println("Length : " +rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " +rect.getArea()); Output :
} Length : 10.0
Width: 20.0
public static void changeRectangle(Rectangle r) { Area: 200.0
r.set(30, 5);
} Length : 30.0
} Width: 5.0
Area: 150.0
Returning Object
• Like any other data datatype, a method can returns object.
• In java, a method can return any type of data, including objects
class ObjectReturnDemo {
int a;
ObjectReturnDemo(int i) {
a = i;
}
/ / This method returns an object
ObjectReturnDemo incrByTen() {
ObjectReturnDemo temp = new ObjectReturnDemo(a+10);
return temp;
}
}
/ / Driver class
public class Test {
public static void main(String args[]) {
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;
ob2 = ob1.incrByTen(); Output:
System.out.println("ob1.a: " +ob1.a);
System.out.println("ob2.a: " +ob2.a); ob1.a: 2
} ob2.a: 12
}
Array of Objects

• The array of objects, as defined by its name, stores an array of


objects.
• An object represents a single record in memory, and thus for
multiple records, an array of objects must be created.
• It must be noted, that the arrays can hold only references to the
objects, and not the objects themselves.
• Declaring An Array Of Objects In Java
• We use the class name Object, followed by square brackets to
declare an Array of Objects.
Object[] JavaObjectArray;
• Another declaration can be as
follows: Object JavaObjectArray[];
Array of Objects
class JavaObjectArray
{ public static void main(String args[])
{ Account obj[] = new Account[1] ;
obj[0] = new Account();
obj[0].setData(1,2);
System.out.println("For Array Element 0");
obj[0].showData();
}
}
class Account
{ int a;
int b;
public void setData(int c,int d) {
a=c;
b=d;
}
public void showData() Output:
{ System.out.println("Value of a ="+a); For Array Element 0
System.out.println("Value of b ="+b); Value of a: 1
Value of b: 2
}
}
Static Data Members
• The static keyword is a non-access modifier used for methods and
attributes.
• Static methods/attributes can be accessed without creating an object of a
class.
• You can create a static field/data members by using the keyword static.
• The static fields have the same value in all the instances of the class.
• These are created and initialized when the class is loaded for the first time.
• you can access static fields using the class name (without instantiation).

• Example
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
}
Static Methods
• You can create a static method by using the keyword static.
• Static methods can access only static fields, methods.
• In Java, static members are those which belongs to the class and you can access
these members without instantiating the class.
• Toaccess static methods there is no need to instantiate the class, you can do it just
using the class name.
• Example
public class MyClass {
public static void sample(){
System.out.println("Hello");
}
public static void main(String args[])
{ MyClass.sample();
}
}
Forward Declaration
• In computer programming, a forward declaration is a declaration of an
identifier (denoting an entity such as a type, a variable, a constant, or a
function) for which the programmer has not yet given a complete
definition.
Forward Declaration
Example
/ / Forward Declaration of the sum()
void sum(int, int);
/ / Usage of the sum
void sum(int a, int b) {
/ / Body
}
• In C++, Forward declarations are usually used for Classes.
• In this, the class is pre-defined before its use so that it can be called and
used by other classes that are defined before this.
/ / Forward Declaration class A
class A;
/ / Definition of class A
class A {
/ / Body
};
Forward Declaration
#include <iostream> int sum(A m, Bn) {
using namespace std; int result;
result = m.y + n.x;
/ / Forward declaration return result;
class A;
}
class B;
int main() {
class B { B b;
int x; A a;
public: a.getdata(5);
void getdata(int n) {
b.getdata(4);
x = n; cout << "The sum is : " << sum(a,b);
} return 0;
friend int sum(A, B); }
};

class A {
int y;
• Output:The sum is : 9
public:
void getdata(int m) {
y = m;
}
friend int sum(A, B);
};
Forward Declaration
class Test2 {
public static void main(String[] args) {
Test1 t1 = new Test1();
t1.fun(5);
}
}
class Test1 {
void fun(int x) {
System.out.println("fun() called: x = " +x);
}
}
Output: fun() called: x = 5
• The Java program compiles and runs fine.
• Note that Test1 and fun() are not declared before their use.
• Unlike C++, we don’t need forward declarations in Java. Identifiers (class
and method names) are recognized automatically from source files
Class as Abstract DataTypes(ADT’s)

• Abstract Data type (ADT) is a type (or class) for objects


whose behaviour is defined by a set of value and a set of
operations.
• The definition of ADT only mentions what operations are to
be performed but not how these operations will be
implemented.
• It does not specify how data will be organized in
memory and what algorithms will be used for
implementing the operations.
• It is called “abstract” because it gives an implementation-
independent view.
• The process of providing only the essentials and hiding the
details is known
as abstraction.
Classes as Objects
• Java 7 has come up with a new class Objects that have 9 static utility
methods for operating on objects.
• These utilities include null-safe methods for computing the hash code of
an object, returning a string for an object, and comparing two objects
• Using Objects class methods, one can smartly
handle NullPointerException and can also show customized
NullPointerException message
• public final class Objects extends Object
• The java.lang.Object class is the root of the classhierarchy.
• Every class has Object as a superclass.
• Methods from object class are clone(), equals(), finalize(), getClass(),
hashCode(), notify(), notifyAll(), toString(), wait() wait(long
timeout),wait(long timeout, int nanos)

You might also like