KEMBAR78
Chapter Three | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
7 views36 pages

Chapter Three

Uploaded by

nahit533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views36 pages

Chapter Three

Uploaded by

nahit533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter Three

Objects & Classes

Compiled By: Nigusu Y. (Nigusu.Yitayal@inu.edu.et )

1
Defining/Creating/Declaring a Class
o Class is created by using the keyword class.
Syntax:
class ClassName { Example:
// declare instance variables public class Course
type var1;
{
type var2;
// ... public void displayMessage()
type varN; {
// declare methods
System.out.println( “OOP with Java!”);
type method1(parameters) {
// body of method }
} public static void main(String args[])
type method2(parameters) {
{
// body of method
} Course oop= new Course ();
// ... oop. displayMessage();
type methodN(parameters) {
}
// body of method
} } 2
}
Creating/Declaring an Object
✓ Objects are created with new keyword.
✓ The new operator dynamically allocates memory for an object and returns a
reference to it.
✓ Thus , in Java, all class objects must be dynamically allocated.
✓ Syntax to create Object:
ClassName obj = new ClassName( ); // Allocate class object
obj.MethodName(); //Calling/invoking the Method
Alternatively,
ClassName obj ; /*declare reference to object contains null value, which
indicates that it does not yet point to an actual object*/
obj = new ClassName( ); // Allocate class object
Example:
Course c = new Course(); //Creating object called c for class Course
c.displayMessage(); //Calling the displayMessage() method
✓The object creation statement has three3 parts: Declaration, Instantiation and
Initialization.
1. Declaration: Associates a variable name with an object type.

▪ Classes in java are also types so declare class type variable as:

Course c; //c is a variable used to refer Course object

▪ Declaring a object variable (Course c; ) do not create any object until assigned with a new
keyword.

2. Instantiation

▪ The new operator instantiates a class by allocating a memory for a new object.

Course c = new Course(); //Create object called c & allocate memory to that object

▪ Instantiating a class means creating an object/Instance of a class.


3. Initialization
▪ The object is always initialized by calling a constructor.
▪ A constructor is a special method which has a same name as class and used to initialize the
variables of that object.
▪ Course class object is initialized by calling the constructor of Course class: Course( );
4
Example:
public class Course
{
String name;
public Course(String name)
{
this.name =name;
}
public static void main(String args[] )
{
Course c1 = new Course("Object Oriented Programming" );
System.out.println( “Course name is "+ c1.name);
}
5
Class and Instance Variables
✓ Variables are areas allocated by the computer memory to hold data.
✓ There are three kinds of variables.
• Local variables
• Class/static variables
• instance variables
o Local variables
▪ These variables are declared inside the function or main function of the
programs.

▪ Local variables were accessed inside the function with its defined
/declared and called after creating the6 instance of class/object.
Class Variables
✓ The runtime system allocates class variables once per class regardless of the
number of instances created of that class.

✓ The system allocates memory for class variables the first time it encounters the
class at class load time.

✓ All instances share the same copy of the class variables.


✓ You can access class variables through an instance or through the class itself.
✓ Static class variables occupy reserves common memory space accepts all the
instances of the class.
✓ To declare a class variable follow the following syntax.

static type variable;


Example: static int a;
static double d;
7
Con’t
o Static variables can be called directly with its class name without creating
instances of class.

o If any object change the value of class variable, the change will effect the
values of all the variables.

o Because the class variable belongs to the class rather than any specific
variable, it can be accessed using the class name such as: -

ClassName.variableName;

o Suppose you have class called Car and class variable called color than you
can access that variable like this: -

Car.color;

8
Instance Variables
▪ Instance variables in Java are non-static variables which are defined in a
class outside any method, constructor or a block.

▪A variable which is created inside the class but outside the method is
known as an instance variable.

▪ Instance variable doesn't get memory at compile time (gets memory at


runtime when an object or instance is created)

▪ Instance/object variables were accessed by creating the instance of the


class/object.

▪ An instance variable can be declared using different access modifiers


available in Java like default, private, public, and protected.
9
public class VariableDemo {
static int x = 12; // class/static variables
int y = 13; // Instance Variables
void print() {
int z = 15; // local variables
System.out.println(z);
} Output
void display() { 12
System.out.println(x); 50
System.out.println(y); 15
}
50
public static void main(String args[]){
13
System.out.println(VariableDemo .x);
VariableDemo.x = 50;
System.out.println(VariableDemo.x);
VariableDemo v = new VariableDemo (); //Creating instance of class/object
v.print();
v.display();
}
10
}
Class Vs Instance Variables

Class variable Instance variable


Class variable is declared by using static Instance variable is declared without static
keyword. keyword.
static int a = 4; int a = 4;

All objects share the single copy of static All objects have their own copy of instance
variable. variable.

Static variable does not depend on the single Instance variable depends on the object for
object because it belongs to a class. which it is available.

Static variable can be accessed without Instance variable cannot be accessed without
creating an object, by using class name. creating an object.

ClassName.variable; ObjectName.variable;
11
Access Modifiers
o Access modifiers define various levels of access between class members and the

outside world (other objects).

o They allow us to define the encapsulation characteristics of an object.

o There are four access modifiers in java:

✓private – Most restrictive, accessible only by its own class

✓protected – Accessible by its own class & derived/sub/child class

✓public - Accessible to anyone, both inside and outside the class (Have global
visibility )

✓default - Accessible to only classes in the same package. No actual keyword for
declaring default access modifier, applied by default in the absence of any
12
access modifier.
Java Constructor
o A Constructor is a special method in java class that is used to initialize a new

object variables.

✓ A constructor must have the same name as the class itself.


✓ Constructors do not have a return type not even void.
✓ Constructors are invoked using the new operator when an object is created.
✓ You cannot call a constructor directly, it can only be called by using the new
operator during class instantiation
Example: if you have Color class the constructor of color class is also Color( );

o A Java program will automatically create a constructor if it is not already defined

in the program by run time system.


13
Default Constructor
oA default constructor is automatically provided by Java if no other
constructor is explicitly defined in the class.

o It takes no arguments and initializes the object with default values (e.g.,
null for reference types, 0 for numeric types, false for Boolean).

o Once you define your own constructor, the default constructor is no longer used.
Example:
public class Data
{
public Data() {
System.out.println("No-Args Constructor");
}
public static void main(String[] args) {
Data d = new Data();
}
} 14
Parametrized Constructor
o Constructor which has a specific number of parameters is called a
parameterized constructor.

o The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.

o The compiler will determine at run time which constructor to call by matching
the number and type of arguments you are passing into the constructor.

o Java this keyword is used to invoke any method or variable of current class.
o The this keyword special reference value used inside any instance method to
refer to the current object .

15
//Parametrized constructor demo
public class Car
{
int modelYear;
String modelName;
public Car(int year, String name) {
this.modelYear = year;
this.modelName = name;
}
public static void main(String[] args)
{
Car myCar = new Car(1969, “Suzki");
System.out.println (myCar.modelYear );
System.out.println (myCar.modelName);
}
16
}
The syntax of method is: -

this.methodname( );

The syntax of variable is: -

this.variablename = 7;
o The this keyword can be used where a reference to an object of the current class
type is required .
o The keyword this is used to reference a field/method from inside the same class.
o Within an instance method or a constructor, this is a reference to the current
object the object whose method or constructor is being called.
o You can refer to any member of the current object from within an instance
method or a constructor by using the this keyword or without using the this
keyword.
17
import java.util.Scanner;
public class Addition {
int x,y;
public Addition (int x, int y){
this.x = x;
this.y = y; }
public void addition(int num1, int num2) {
int sum;
sum = num1 + num2;
System.out.println("sum is " + sum); }
public static void main(String args[]) {
int a, b;
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers");
a = input.nextInt();
b = input.nextInt();
Addition ad = new Addition (a,b);
ad. addition(a, b);
} } 18
Java Methods
✓A method is a group of programming language statements with a given name.
✓ Methods are functions that operate on instances of classes in which they are
defined.

✓ Objects can communicate with each other using methods and can call methods in
other classes.

✓ A method is a separate piece of code that can be called by a main program or any
other method to perform some specific function.

✓ Methods are subroutines that manipulate the data defined by the class and, in
many cases, provide access to that data.

✓ Why do we need to create methods? Why don't we just place all the code inside
one big method? The heart of effective problem solving is in problem
19
decomposition.
Defining Methods
o The type, name and parameters together is referred to as the signature of the method (
Method Declaration).

o They are , name of the method, type of object or primitive type the method returns, a list of
parameters and body of the method.

o Syntax:

Example:
double computeArea(int base, int height) {
double A;
return A = (base*height)/2;
20
}
Calling Methods
▪ The methods are accessed using the dot notation using object.
Syntax: obj.methodName ( arg1, arg2 );
o Example:
public class Area {
int len = 10;
int wid = 10;
public void calculateArea ( ) { // creating calculateArea method
int area = len * wid ;
System .out .println( “ The area of rectangle is “ + area + “ sq. cms “);
}
public static void main ( String args [ ] ) {
Area a= new Area ( ) ; //Creating object a for class Area
a.calculateArea ( ) ; //Calling/Invoking the Method
} 21
}
Method Parameters
o Parameters refers to the list of variables in a method declaration.
double Area(double height, double width) // 2 parameters height & width
double Area(double radius) //1 parameter radius
double findSquareRoot(double num ) // 1 parameter num
double isPerfect(int num ) //1 parameter num
int isEven(int num ) // 1 parameter num
oThe number of arguments in a method call must match the number of parameters in
the parameter list of the called method’s declaration.
oAlso, the argument types in the method call must be “consistent with” the types of
the corresponding parameters in the method’s declaration

22
Con’t
oFormal parameter: parameters written in the method header.
✓Parameters are variables passed to method.
int Area(int length, int width);

o Actual parameter: are arguments written in calling methods.


✓The actual values that are passed in when the method is called.
Area (length, width) ;
Example 1:
int x=3, y=5;
Addition A = new Addition(x, y) ; // x & y are argument passed to method
A. Add(); //Call the Method Add()

23
Demonstration of Methods
public class Point {
int x,y;
public void init (int x , int y) {
this.x = x;
this.y = y; }
public void display ( )
{
System.out.println (" x = "+ x);
System.out.println (" y = "+ y ); }
public static void main(String[] args) {
Point P = new Point() ;
P.init(4,3);
P.display() ;

} } Output x=4
24 y=3
Passing arguments to methods
o Argument and objects can be passed to the methods in to two techniques.
❖Pass by value
• Copies the value of an argument into the formal parameter of the subroutine.

• Therefore, changes made to the parameter of the methods have no effect on


the argument
❖Pass by reference
• With a reference to an argument (not the value of the argument) is passed to the
parameter. (Passing the address of the parameters, not the value)

• Inside the subroutine, this reference is used to access the actual argument
specified in the call.

• Changes made to the parameter will affect the argument used to call the
25
method.
Example: Pass by value
class Sum
{ Program Output:
int x=50; before change 50
after change 50
void change(int x) { //called method
// this local variable a is subject to change in its value
x=x+100; //changes will be in the local variable only
}
public static void main(String args[]) //calling method
{
Sum v=new Sum();
System.out.println("before change "+v.x);
//The value of ‘x' will still be unchanged since the passing parameter is a primitive type.
v.change(500);
System.out.println("after change "+v.x);
} }
26
Example: Pass by reference
class Sum
{
int x=50;
// Original value of ‘x' will be changed since objects passed by reference.
void change(Sum ref) //called method
{
ref.x=ref.x+100; //changes will be in the instance variable
}
public static void main(String args[]) //calling method
{
Sum ref=new Sum();
System.out.println("before change "+ref.x);
ref.change(ref); //passing the object as a value using pass-by-reference
System.out.println("after change "+ref.x); Program output
before change 50
} 27
after change 150
}
Method Body
o The body of a method is a block specified by curly brackets.
o The body defines the actions of the method.
int isEven(int num ) {
if(num%2==0) {
System.out.println(“The Number is Even.”);
Method body
}
else {
System.out.println(“The Number is Even.”);
}
}
o The main method is a special method where a Java program execution always starts.
public static void main(String[] args) {
//. . .
} 28
Method Return Type
o The return type of a method may be any data type.
o The type of a method designates the data type of the output it produces.
Syntax: return expression;

o Methods can also return nothing in which case they are declared void.
Example:
double divide(double a, double b) {
double answer;
answer = a / b;
return answer;
}
oA method of type void has a return statement without any specified value. i.e.
return;
o Any method declared void doesn't return29a value.
Static vs Instance Methods
s
Static(class) Method Instance(normal) Method
Static methods are declared by using static instance methods are declared without static
keyword. keyword.
static type method( ); type method( );

All objects share the single copy of static All objects have their own copy of instance
method. method.

Static method does not depend on the single Instance method depends on the object for which
object because it belongs to a class. it is available.

Static method can be invoked without creating an Instance method cannot be invoked without
object, by using class name. creating an object.
ClassName.method( ); ObjectName.method( );

Static methods cannot call non-static methods. Non-static methods can call static methods.

Static methods cannot access not-static variables. Non-static methods can access static variables.

30
Static methods cannot refer to this or super. Instance methods can refer to this and super.
o When to declare variable/method as static?
▪ When value of the variable remains the same for all class instance
created & being used in every instance. They’ll be loaded when a
class loads.
▪ Static tells compiler there’s exactly one copy of this variable in
existence, no matter how many times class has been instantiated.
▪ Static method or variable is not attached with specific object, but
to class as a whole. They are allocated when the class is loaded.
▪ Static methods are declared when the behaviour of method doesn’t
change for each object created [i.e. behaviours of method remain
the same for all instances created.]
31
// Demonstrate of constructors, variables, methods and blocks
public class Even {
int x;
public Even(int x) { //Constructor
this.x = x; }
public void evenOdd(int num) { //Method
if (num % 2 == 0) {
System.out.println("the number is even");
} else {
System.out.println("the number is odd");
} }
public static void main(String[] args) throws IOException {
String num1;
int a;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number");
num1 = br.readLine();
a = Integer.parseInt(num1);
Even ev = new Even(a); //argument a
ev.evenOdd(a); //Method calling
32
}}
Object References
o A reference is an address that indicates where an object's variables and methods
are stored.

oA class name can be used to specify the type of a variable in a declaration


statement, the type of a formal parameter, or the return type of a method.

o However, declaring a variable does not create an object! This is an important


point, which is related to this Very Important Fact:

o In JAVA, no variable can ever hold an object. (A variable can only hold a
reference to an object.)

o Instead of holding an object itself, a variable holds the information necessary to


find the object in memory.

o This information is called a reference or pointer to the object.


33
Con’t
o When one object variable is assigned to another, only a reference is copied. The
object referred to is not copied.

o We can assign value of reference variable to another reference variable.


• Reference Variable is used to store the address of the variable.
• Assigning Reference will not create distinct copies of Objects.
• All reference variables are referring to same Object.
o An object reference variable does not:
• Create Distinct Objects.
• Allocate Memory
• Create duplicate Copy
34
Rectangle r1 = new Rectangle ();
Rectangle r2 = r1;

o r1 is reference variable which contain the address of Actual Rectangle Object.


o r2 is another reference variable
o r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does
not create duplicate object , nor does it allocate extra memory.

o It simply makes r2 refer to the same object as does r1.


o Any changes made to the object through r2 will affect the object to which r1 is referring.

35
//Object references demo
class Rectangle
{
Output:
int length; Value of R1's Length : 20
int breadth; Value of R2's Length : 20

public static void main(String args[])


{
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
r1.length = 10;
r2.length = 20;
System.out.println("Value of R1's Length : " + r1.length);
System.out.println("Value of R2's Length : " + r2.length);
}
}
36

You might also like