Wa0008
Wa0008
Wa0008
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
• Public
– The class is accessible by any other class
class Student{
• 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
• Instead, we use the getName() and setName() methods to acccess and update
the variable:
• Output: "John"
Encapsulation
Why Encapsulation?
• 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
• 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
• Output: 8
Adding a Method that Takes Parameters
‘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);
}
}
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
• 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)