lecture 5
TRANSCRIPT
![Page 1: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/1.jpg)
Lecture-5 & 6Instructor Name:
Object Oriented Programming
![Page 2: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/2.jpg)
Today’s Lecture
Components of Class
Fields
Methods Main() Method, Setter Method, Getter Method, immutator.
Calling Method in same class Main method
Calling Method in other class. Creating Objects from class
2
![Page 3: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/3.jpg)
Class & Methods
Messages to Object
3
Object<7_series_BMW>
“Start the engine of the BMW”
Start_Engine
![Page 4: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/4.jpg)
Class & Methods
Method of Class
4
Class<CAR>
Start_Engine
![Page 5: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/5.jpg)
Class & Methods
Behavior Behavior is how an object acts and reacts, in terms of state
changes and interactions with other objects.
An operation is some action that one object performs upon another in order to elicit a reaction.
We will use the word method to describe object behavior in java.
Invoking a method causes the behavior to take place.
5
![Page 6: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/6.jpg)
Class & Methods
What is a Method? Method defines the behaviour or basic functionality of the
class.
Methods have two parts: a header and a body. Methods belong to a class
– Defined inside the class Heading
– Return type (e.g. int, float, void)– Name (e.g. nextInt, println)– Parameters (e.g. println(…) )– More…
Body– enclosed in braces {}.– Declarations and/or statements. 6
![Page 7: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/7.jpg)
Class & Methods
Writing your own methods The general form of method definition is
scope type name(argument list) { statements in the method body}
where scope indicates who has access to the method, type indicates what type of value the method returns, name is the name of the method, and argument list is a list of declarations for the variables used to hold the values of each argument.
The most common value for scope is private, which means that the method is available only within its own class. If other Class need access to it, scope should be public instead.
If a method does not return a value, type should be void. Such methods are sometimes called procedures.
7
![Page 8: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/8.jpg)
Class & Methods
Returning value from methods You can return a value from a method by including a return
statement, which is usually written as
return expression; where expression is a Java expression that specifies the value
you want to return.
As an example, the method definition
private double feetToInches(double feet) { return 12 * feet;}
converts an argument indicating a distance in feet to the equivalent number of inches, relying on the fact that there are 12 inches in a foot.
8
![Page 9: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/9.jpg)
Class & Methods
Method Examplespublic class Dog {
private String name;private int age;
public setName(String dogName){name=dogName;
}
public String getName(){return name;
} }
public class CreateDog {public static void main (String args[]){
Dog myDog = new Dog();}
} 9
![Page 10: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/10.jpg)
Class & Methods
Methods Invocation Invoked as operations on objects/Class using the dot ( . )
operator
reference.method(arguments) “Reference” can either be the class name or an object
reference belonging to the class Inside the class: “reference” can be ommitted
10
![Page 11: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/11.jpg)
Class & Methods
Methods Overloading A class can have more than one method with
the same name as long as they have different parameter list.
public class Pencil {. . .public void setPrice (float newPrice)
{price = newPrice;
}
public void setPrice (Pencil p) {price = p.getPrice();
}}
How does the compiler know which method you’re invoking? — compares the number and type of the parameters and uses the matched one
11
![Page 12: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/12.jpg)
Class & Methods
Methods – Parameter Value Parameters are always passed by value.
public void method1 (int a) { a = 6;}
public void method2 ( ) { int b = 3; method1(b); // now b = ?
// b = 3}
• When the parameter is an object reference, it is the object reference, not the object itself, getting passed.
12
![Page 13: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/13.jpg)
Method Example – (Parameter is Object Reference)
13
- What is passed is the object reference, and it’s passed in the manner of “PASSING BY VALUE”!
class PassRef{public static void main(String[] args) { Pencil plainPencil = new Pencil("PLAIN"); System.out.println("original color: " + plainPencil.color);
paintRed(plainPencil);
System.out.println("new color: " + plainPencil.color);}
public static void paintRed(Pencil p) { p.color = "RED"; p = null;}
}
plainPencil
plainPencil
plainPencil p
plainPencil p
color: PLAIN
- If you change any field of the object which the parameter refers to, the object is changed for every variable which holds a reference to this object
color: PLAIN
color: RED
color: RED NULL
p
- You can change which object a parameter refers to inside a method without affecting the original reference which is passed
![Page 14: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/14.jpg)
Class & Methods
Accessor & Mutator Methods Accessor methods are those which returns information to the
caller about the state of the object; they provide access to information about the state of object
Accessor usually contains the return statement in order to pass back that information.
getName()
Mutator method is one that change the state of an object.
The most basic form of object is one that takes a single parameter whose value is used to directly overwrite what is stored in the object’s field.
setName()
14
![Page 15: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/15.jpg)
Class & Methods
Accessor Methods
15
![Page 16: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/16.jpg)
Class & Methods
Mutator Methods
16
![Page 17: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/17.jpg)
Class & Methods
Keyword - thisCan be used only inside methodWhen call a method within the same class,
don’t need to use this, compiler do it for you.
When to use it?– method parameter or local variable in a method
has the same name as one of the fields of the class
– Used in the return statement when want to return the reference to the current object.
17
![Page 18: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/18.jpg)
Class & Methods
Keyword – this Example 1
When a method parameter or local variable in a method has the same name as one of the fields of the class, you must use this to refer to the field.
18
class A{int w; public void setValue (int w) {
this.w = w; //same name!}
}
![Page 19: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/19.jpg)
Class & Methods
Keyword – this Example 2
19
class Exp{public int i=0; public Exp increment () {
i++;return this; // return current object
}
public static void main (String[] args){Exp e = new Exp();int v = e.increment().increment().i; // v=2!!
}}
![Page 20: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/20.jpg)
Object Initialization
20
When objects are created, the initial value of data fields is unknown unless its users explicitly do so. For example,– ObjectName.DataField1 = 0; // OR– ObjectName.SetDataField1(0);
In many cases, it makes sense if this initialisation can be carried out by default without the users explicitly initializing them.– For example, if you create an object of the class called
“Counter”, it is natural to assume that the counter record-keeping field is initialized to zero unless otherwise specified differently.
class Counter{
int CounterIndex;…
}Counter counter1 = new Counter();
– What is the value of “counter1.CounterIndex” ? In Java, this can be achieved though a mechanism called
constructors.
![Page 21: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/21.jpg)
Class & Constructor
What is a Constructor?A special method automatically called when an
object is created by new() Java provide a default one that takes no
arguments and perform no special initialization – Initialization is guaranteed– All fields set to default values: primitive types to 0
and false, reference to null
21
![Page 22: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/22.jpg)
Class & Constructor
What is a Constructor? Constructor in java is a special type of method that is used to
initialize the object.
Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.
The constructors are responsible for ensuring that an object is set up properly when it is first created.
The construction process is also known as initialization.
If a constructor is not defined in the class, Java will create a default constructor that will invoke automatically when object is create.
22
![Page 23: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/23.jpg)
Class
What is a Constructor? Constructor is called at the time of object creation.
Once object has been created, the constructor plays no further role in that object life and can not be called on it.
One of the distinguished feature of constructor is that it has the same name as the class in which they are defined.
In the constructor the fields are initialized with default values or external information passed into object at the time of creation.
23
![Page 24: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/24.jpg)
Class
Constructor Rules and Example Constructor name must be same as class name. Constructor must have no explicit return type.
public class Dog {
private String name;private int age;
public Dog(){name=NULL;age=0;
}
rest of class }
In the constructor the fields are initialized with default values or external information passed into object at the time of creation.
24
![Page 25: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/25.jpg)
Class
Types of Constructor There are two types of Constructor
1. Default Constructor (No arguments required)A constructor that have no parameter (as in previous
slide)2. Parameterized Constructor
A constructor that have parameter. Example public Dog(String name, int age){
this.name=name;this.age=age;
}
Class Activity Can you guess what types some of the Book class’s fields
might be, from the parameters in its constructor? Can you assume anything about the names of its fields?
25
![Page 26: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/26.jpg)
Class & Constructor
Constructor Example
26
class Circle{double r; public static void main(String[] args){
Circle c2 = new Circle(); // OK, default constructor
Circle c = new Circle(2.0); //error!!}
}
![Page 27: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/27.jpg)
Class & Constructor
Constructor Example
27
class Circle{double r; public Circle (double r) {
this.r = r; //same name!} public static void main(String[] args){
Circle c = new Circle(2.0); //OKCircle c2 = new Circle(); //error!!, no more default
}}
Circle.java:8: cannot resolve symbolsymbol : constructor Circle ()location: class Circle
Circle c2 = new Circle(); //error!! ^
1 error
![Page 28: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/28.jpg)
Class & Constructor
Constructor Example
28Multiple Constructors Now. What is this?
class Circle{double r; public Circle(){
r = 1.0; //default radius value;}public Circle (double r) {
this.r = r; //same name!} public static void main(String[] args){
Circle c = new Circle(2.0); //OKCircle c2 = new Circle(); // OK now!
}}
![Page 29: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/29.jpg)
Class
Exercise To what class the following constructor belong?
Public Student (String name)
Suppose that the class Pet has a field called name that is of type String. Write an assignment statement in the body of the following constructor so that the name field will be initialized with the value of the constructor’s parameter.
public Pet(String petsName){
} Write the constructor header for the following constructor
call. Date(“September”,08,2015)
Try to give meaningful name to the parameters29
![Page 30: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/30.jpg)
Class & Constructors
Constructor Overloading One context in which you will regularly need to use
overloading is when you write constructors for your Class.
Constructors are methods that can be overloaded, just like any other method in a class.
In most situations, you will want to generate objects of a class from different sets of initial defining data
Overloading constructors provides a way to create objects with or without initial arguments, as needed
30
![Page 31: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/31.jpg)
Class & Constructors
Constructor Overloading Example 1public class Employee { public Employee (String n, double a) { name = n; salary = a; } public Employee ( ) { name = “ “; salary = 0; }} 31
![Page 32: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/32.jpg)
Class & Constructors
Constructor Overloading Example 2public class MyClass{ int x; MyClass() { System.out.println("Inside MyClass() constructor."); x=0; } MyClass(int i) { System.out.println("Inside MyClass(int)
constructor."); x=i; } 32
![Page 33: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/33.jpg)
Class & Constructors
Constructor Overloading Example 2 MyClass(double d) { System.out.println("Inside MyClass(double)
constructor."); x=(int)d; } void getXvalue() { System.out.println("The value of the instance
variable \nof the object " +this+" is "+x+"."); }}
This prints the address/reference of object 33
![Page 34: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/34.jpg)
Class & Constructors
Constructor Overloading Example 2
34
public class MyClassTest{ public static void main(String[] args) { MyClass first=new MyClass(); MyClass second=new MyClass(52); MyClass third=new MyClass(13.6); first.getXvalue(); second.getXvalue(); third.getXvalue(); }}
![Page 35: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/35.jpg)
Class & Constructors
Constructor Overloading Example 2
35
OUT PUTInside MyClass() constructor.Inside MyClass(int) constructor.Inside MyClass(double) constructor.The value of the instance variable of the object TimoSoft.MyClass@19821f is 0.The value of the instance variable of the object TimoSoft.MyClass@addbf1 is 52.The value of the instance variable of the object TimoSoft.MyClass@42e816 is 13.
![Page 36: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/36.jpg)
Class & Constructors
Constructor Overloading One common reason that constructors are
overloaded is to allow one object to initialize another.
The need to produce an identical copy of an object occurs often:
36
![Page 37: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/37.jpg)
Class & Constructors
Constructor Overloading Example 3
37
public class MyClass{ int x, y; MyClass() { System.out.println("Inside MyClass() constructor."); x=0; y=0; } MyClass(int i, int j) { System.out.println("Inside MyClass(int) constructor."); x=i; y=j; }
![Page 38: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/38.jpg)
Class & Constructors
Constructor Overloading Example 3
38
MyClass(MyClass obj) { System.out.println("Inside MyClass(MyClass) constructor."); x=obj.x; y=obj.y; } void getXYvalues() { System.out.println("The value of the instance variables \nof the object " +this+" are "+x+" and "+y+"."); }}
![Page 39: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/39.jpg)
Class & Constructors
Constructor Overloading Example 3
39
public class MyClassTest{ public static void main(String[] args) { MyClass first=new MyClass(); MyClass second=new MyClass(52, 18); MyClass third=new MyClass(second); first.getXYvalues(); second.getXYvalues(); third.getXYvalues(); }}
![Page 40: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/40.jpg)
Class & Constructors
Constructor Overloading Example 3
40
OutputInside MyClass() constructor.Inside MyClass(int) constructor.Inside MyClass(MyClass) constructor.The value of the instance variables of the object TimoSoft.MyClass@19821f are 0 and 0.The value of the instance variables of the object TimoSoft.MyClass@addbf1 are 52 and 18.The value of the instance variables of the object TimoSoft.MyClass@42e816 are 52 and 18.
![Page 41: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/41.jpg)
Program Structure
41
• A program consists of one or more Class
• Typically, each class is in a separate .java file
File File
File
FileClassVariable
sConstructors
Methods
Variables
Variables
Statements
Statements
Program
![Page 42: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/42.jpg)
Home Assignment/ Self Review Exercise
42
1. Write out a class Person. Write out a constructor that should take two parameters. The first is of type String and is called myName. The second is of type int and is called myAge. The first parameter should be used to set the value of a
field called name, and the second should set a field called age. You don’t have to include the definitions for the fields, just the text of the constructor.
2. Write an accessor method called getName that returns the value of a field called name, whose type is String.
3. Write a mutator method called setAge that takes a single parameter of type int and sets the value of a field called age.
4. Write a method called printDetails for a class that has a field of type String called name. The printDetails method should print out a string of the form “The name of this person is”, followed by the value of the name field. For instance, if the value of the name field is “Ali”, then printDetails would print:
The name of this person is Ali
![Page 43: Lecture 5](https://reader035.vdocuments.us/reader035/viewer/2022070509/58a664141a28ab1c5b8b6af3/html5/thumbnails/43.jpg)
43