0% found this document useful (0 votes)
18 views83 pages

Refresher Session - 2021B

samBot.turnRight(); • Tell samBot to move forward 3 steps → samBot.moveForward(3); Now samBot has reached his destination!

Uploaded by

1paper 1pen
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)
18 views83 pages

Refresher Session - 2021B

samBot.turnRight(); • Tell samBot to move forward 3 steps → samBot.moveForward(3); Now samBot has reached his destination!

Uploaded by

1paper 1pen
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/ 83

Material name_Refresher Module

Please watch our tutorial on how to use our bot in best way.
https://www.linktr.ee/reccobot

Recco Bot
Filename:1_JAVA Refresher

Please watch our tutorial on how to use our bot in best way.
https://www.linktr.ee/reccobot

Recco Bot
Tutorial-1: Crash Course on Java
Slide Credits: Internet / Chetan Arora
Java Architecture

• Java programming environment

2
Java Architecture

• Java platform (Java Virtual Machine + Java API)

3
Object Oriented Programming
• The data has the principal role

• Methods belong to the data, without the data, the method does
not have any meaning (Except static methods)

• Data and methods together make up the object.

• OOP tries to model the real world.


Real World

Real world
entities
Objects have states

Lyin
g

Red Broken

Happy
il
l Hooke
Objects have behavior
Hello, Nice to da da
I am meet you …
John

Grrrrrrrr Vroemm
Object Properties
• Identity
• State
• Behavior on
off

myLamp

Object is an abstraction of a real world entity


OOP Modelling: Objects and Classes
• Each object represents an abstraction
• A “black box”: hides details we do not care about
• Allows a programmer to control programs’ complexity - only
think about salient features

Methods

Object
boundary

data
OOP Modelling: Objects and Classes
• Class – Category/Bluprint/Contract
• Properties/states data
methods
• Functionality/Services (examines/alters state)

• Object - Individual/unique thing (an instance of a class)


• Particular value for each property/state
• Functionality of all members of class
OOP Modelling: Objects and Classes
A class An object
(the (the
concept) realization)
Bank John’s Bank Account
Account Balance: $5,257

Multiple objects Bill’s Bank Account


from the same Balance: $1,245,069
class
Mary’s Bank Account
Balance: $16,833
OOP Modelling: Program
• We write programs by modeling problem as set of collaborating
components:
• We determine what the building blocks are
• Put them together so they cooperate properly
• Like building with smart Legos, some of which are pre-defined,
some of which we design!
OOP Modelling: Program
• Program/Software System Created (instantiated) from class
• Set of objects definitions
• Which interact with each other
David: One object will send a message to
Say Person another object asking it to do a
your particular task. The first object does
name not need to know how the task is done
(only how to request that it be done.)
Ayse David
This corresponds to calling one of the
“David” second object’s methods!
Abstraction
• An abstraction hides (or ignores) unnecessary details
• Denotes the essential properties of an object
• One of the fundamental ways in which we handle complexity
• Objects are abstractions of real world entities
• Programming goal: choose the right abstractions

Abstraction A car consists of four wheels


an engine, a steering wheel
and brakes.
Example

hom dow writ


Methods up
e n e
Object
boundary
location direction
data
penDown
Encapsulation Public

• The data belonging to an object is


hidden, so variables are private
• Methods are public hom dow writ
up
e n e
• We use the public methods to
change or access the private data.
• No dependence on implementation
• Encapsulation makes programming location direction
easier
• As long as the contract is the penDown
same, the client doesn’t care Private
about the implementation
Creating Objects in Java
Defining Car Class
• What are the common attributes of cars?

• What are the common behaviors of cars?


Class Car
Car class name

color
speed attributes
power

drive
turn right operations
turn left
stop
Java Syntax
public class Car Car
{
// attribute declarations
private String color;
String color
private int speed; int speed
private int power; int power
// method declarations
public void drive() drive()
{ // …. turnRight()
} turnLeft()
public void turnRight() stop()
{ // ….
}
Class Pencil
Pencil Name

int location attributes


String direction

home()
up() methods
down()
write()
Declaring objects
• A class can be used to create objects
• Objects are the instances of that class

Car

String color
int speed
int power new
drive()
turnRight()
turnLeft()
stop()
Defining and Calling Methods on Objects
• Calling methods
• Declaring and defining a class
• Instances of a class
• Defining methods
• The this keyword
Meet samBot

• samBot is a robot who lives in a


2D grid world
• He knows how to do two things:
• move forward any number of steps
• turn right 90o
• We will learn how to communicate
with samBot using Java
samBot’s World

• This is samBot’s world


0 1 2 3 4
• samBot starts in the
0 square at (0,0)
• He wants to get to the
1
square at (1,1)
2 • Thick black lines are
walls that samBot can’t
pass through
Giving Instructions

0 1 2 3 4
• Goal: move samBot from his
starting position to his destination 0
by giving him a list of instructions
• samBot only knows instructions 1
“move forward n steps” and “turn
right” 2

• What instructions should we give


him?
Giving Instructions
Note: samBot moves in the direction her outstretched arm is
pointing; yes, he can move upside down in this 2D world

• “Move forward 4 steps.” 0 1 2 3 4

• “Turn right.” 0
• “Move forward 1 step.”
1
• “Turn right.”
• “Move forward 3 steps.” 2
“Calling Methods”: Sending Messages in Java

• samBot can only handle messages that he knows how to


respond to
• These responses are called methods!
o “method” is short for “method for responding to a message”
• Objects cooperate by sending each other messages.
o object sending message is the caller
o object receiving message is the receiver
“Calling Methods”: Sending Messages in Java
• samBot already has one method for “move forward n steps” and
another method for “turn right”
• When we send a message to samBot to “move forward” or “turn
right” in Java, we are calling a method on samBot.

Hey samBot, turn The method call (message


right!
passed from caller to receiver)

The caller The receiver


(samBot)
Turning samBot right
• samBot’s “turn right” method is called turnRight
• To call the turnRight method on samBot:
• samBot.turnRight();
• To call methods on samBot in Java, need to address him by name!
• Every command to samBot takes the form: You substitute for
anything in < >!
• samBot.<method name(…)>;
; ends Java statement
• What are those parentheses at the end of the method for?
Guiding samBot in Java
• Tell samBot to move forward 4 steps → samBot.moveForward(4);
• Tell samBot to turn right → samBot.turnRight();
• Tell samBot to move forward 1 step → samBot.moveForward(1);
• Tell samBot to turn right → samBot.turnRight();
• Tell samBot to move forward 3 steps → samBot.moveForward(3);

0 1 2 3 4

“pseudocode” 0 Java code

2
Putting Code Fragment in a Real Program
•public class RobotMover {

• Let’s demonstrate this code for real /* additional code */


• First, need to put it inside real Java
program public void moveRobot(Robot samBot) {
samBot.moveForward(4);
• Grayed-out code specifies context in samBot.turnRight();
which samBot executes these samBot.moveForward(1);
instructions samBot.turnRight();
samBot.moveForward(3);
• Also includes samBot’s
}
capability to respond to
}
moveForward and turnRight −
more on this later
Putting Code Fragments in a Real Program
Now we will explain this
part of the code.
public class RobotMover {

/* additional code elided */


• Before, we’ve talked about
objects that handle public void moveRobot(Robot samBot) {
messages with "methods" samBot.moveForward(4);
samBot.turnRight();
samBot.moveForward(1);
samBot.turnRight();
samBot.moveForward(3);
}
}
Class (refresh)
• A class is a blueprint for a
certain type of object public class RobotMover {

• An object’s class defines its /* additional code elided */


properties and capabilities
(methods) public void moveRobot(Robot samBot) {
samBot.moveForward(4);
• So far, we’ve been working samBot.turnRight();
within the class RobotMover samBot.moveForward(1);
samBot.turnRight();
• We need to tell Java about samBot.moveForward(3);
our RobotMover }
}
Declaring and Defining a Class (1/3)
declaration of the RobotMover class
• As with dictionary entry, first declare
term, then provide definition
public class RobotMover {
• First line declares RobotMover class
/* additional code elided */
• Breaking it down:
public void moveRobot(Robot samBot) {
• public indicates that anyone can
samBot.moveForward(4);
use this class samBot.turnRight();
• class indicates to Java that we are samBot.moveForward(1);
about to define a new class samBot.turnRight();
samBot.moveForward(3);
• RobotMover is the name that we }
have chosen for our class }

Note: public and class are Java “reserved words” aka “keywords” and have
pre-defined meanings in Java; we’ll be using Java keywords a lot in the future
Declaring and Defining a Class (2/3)
• Class definition (aka “body”)
defines properties and capabilities of •public class RobotMover {

class •/* additional code elided */


•itis contained within curly braces
•public void moveRobot(Robot samBot) {
that follow the class declaration
• samBot.moveForward(4);
• A class’s capabilities (“what it knows • samBot.turnRight();
• samBot.moveForward(1);
how to do”) are defined by its
• samBot.turnRight();
methods – RobotMover thus far • samBot.moveForward(3);
only knows this very specific •}
moveRobot method
•}
• A class’s properties are defined by
its instance variables – more on
this next week definition of the RobotMover class
Declaring and Defining a Class (3/3)
• General form for a class:

<visibility> class <name> { declaration

<code (properties and


definition
capabilities) that defines class>

• Each class goes in its own file, where name of file matches name of class

o RobotMover class is contained in file “RobotMover.java”


Methods of the Robot class

• public void turnRight() and


public class Robot {
public void moveForward(int
public void turnRight() { numberOfSteps) each declare a
// code that turns robot right method
}
• Since moveForward needs to know
public void moveForward(int numberOfSteps) { how many steps to move, we put
// code that moves robot forward int numberOfSteps within the
} parentheses
/* other code deleted */ • int is Java’s way of saying this
} parameter is an “integer” (we
say “of type integer”)
Classes and Instances (1/3)

• We’ve been saying samBot is a Robot


• We’ll now refer to him as an instance of class Robot
• This means samBot is a particular Robot built
using Robot class as a blueprint
• All Robots (all instances of the class Robot) have
the exact same capabilities: the methods defined in
the Robot class
Classes and Instances (2/3)

The Robot class is


like a blueprint
Classes and Instances (3/3)
We can use the Robot class to build actual Robots - instances of the
class Robot, whose properties may vary (next lecture)

samBot blueBot pinkBot greenBot


Classes and Instances
Method calls are done on instances of the class

instance instance instance instance

samBot blueBot pinkBot greenBot


A variation public class RobotMover {
/* additional code elided */

public void moveRobot(Robot samBot) {


samBot.turnRight();
samBot.moveForward(2);
0 1 2 3 4 samBot.turnRight();
samBot.turnRight();
0 samBot.turnRight();
samBot.moveForward(3);
samBot.turnRight();
1 samBot.turnRight();
samBot.turnRight();
samBot.moveForward(2);
2 samBot.turnRight();
samBot.turnRight();
samBot.turnRight();
samBot.moveForward(2);
}
}
A variation public class RobotMover {
/* additional code elided */

public void moveRobot(Robot samBot) {


samBot.turnRight();
• Lots of code for a simple problem... samBot.moveForward(2);
samBot.turnRight();
• samBot only knows how to turn right, samBot.turnRight();
so have to call turnRight three samBot.turnRight();
samBot.moveForward(3);
times to make him turn left
samBot.turnRight();
• If he understood how to “turn left”, samBot.turnRight();
would be much simpler! samBot.turnRight();
samBot.moveForward(2);
• We can modify samBot to turn left by samBot.turnRight();
defining a method called turnLeft samBot.turnRight();
samBot.turnRight();
samBot.moveForward(2);
}
}
Defining a Method (2/2)
public class Robot {

public void turnRight() {


// code that turns robot right
}

public void moveForward(int numberOfSteps) {


• Adding a new method:
// code that moves robot forward turnLeft
}
• To make a Robot turn left,
public void turnLeft() { tell her to turn right three
//The new code goes here!! times

}
}
The this keyword (1/2)
public class Robot {

public void turnRight() {


// code that turns robot right • When working with
} RobotMover, we were talking
to samBot, an instance of
public void moveForward(int numberOfSteps) {
// code that moves robot forward
class Robot
} • To tell her to turn right, we said
“samBot.turnRight();”
public void turnLeft() {
this.turnRight(); • Why do we now write
this.turnRight();
“this.turnRight();”?
this.turnRight();
}
}
The this keyword (2/2)
• The this keyword is how an
instance (like samBot) can call a
•public class Robot { method on itself
public void turnRight() { • Use this to call a method of Robot
• // code that turns robot right class from within another method of
} Robot class
public void moveForward(int numberOfSteps) { • When samBot is told by, say,
• // code that moves robot forward RobotMover to turnLeft, she
}
responds by telling herself to
•public void turnLeft() {
turnRight three times
• this.turnRight();
• this.turnRight(); means “hey
• this.turnRight();
• this.turnRight();
me, turn right!”
•} • this is optional, but desirable!
}
Summary
Class
declaration
public class Robot {

public void turnRight() {


// code that turns robot right
}

public void moveForward(int numberOfSteps) {


// code that moves robot forward
Class Method
}
definition declaration
public void turnLeft() {
this.turnRight();
this.turnRight(); Method definition
this.turnRight();
}
}
Simplifying our code using turnLeft
public class RobotMover { public class RobotMover {
public void moveRobot(Robot samBot) { public void moveRobot(Robot samBot) {
samBot.turnRight(); samBot.turnRight();
samBot.moveForward(2); samBot.moveForward(2);
samBot.turnRight(); •samBot.turnLeft();
samBot.turnRight(); samBot.moveForward(3);
samBot.turnRight(); •samBot.turnLeft();
samBot.moveForward(3); samBot.moveForward(2);
samBot.turnRight(); •samBot.turnLeft();
samBot.turnRight(); samBot.moveForward(2);
samBot.turnRight(); }
samBot.moveForward(2); }
samBot.turnRight();
samBot.turnRight();
samBot.turnRight();
samBot.moveForward(2); We’ve saved a lot of lines
}
}
of code by using turnLeft!
public class Robot {
turnAround public void turnRight() {
// code that turns robot right
}

• We could also define a public void moveForward(int numberOfSteps) {


method that turns the // code that moves robot forward
}
Robot around 180o.
public void turnLeft() {
• Excercise: Can you this.turnRight();
this.turnRight();
declare and define the this.turnRight();
method turnAround }

// your code goes here!


// …
// …
// …
}
•public class Robot {
turnAround public void turnRight() {
// code that turns robot right
}

• Now that the Robot class has public void moveForward(int numberOfSteps) {
the method turnAround, we // code that moves robot forward
}
can call the method on any
Robot public void turnLeft() {
this.turnRight();
• There are other ways of this.turnRight();
implementing this method that this.turnRight();
•}
are just as correct
public void turnAround() {
this.turnRight();
this.turnRight();
}
}
public class Robot {
turnAround public void turnRight() {
// code that turns robot right
}
• Instead of calling turnRight,
could call our newly created public void moveForward(int numberOfSteps) {
method, turnLeft // code that moves robot forward
}
• Both of these solutions are
equally correct, in that they will public void turnLeft() {
turn the robot around 180o this.turnRight();
this.turnRight();
• How do they differ? When we this.turnRight();
try each of these }
implementations with samBot,
what will we see in each case? public void turnAround() {
this.turnLeft();
this.turnLeft();
}
}
Using Classes and Objects
Where did all these instances come from?

● We know how to send messages to an instance of a class by calling


methods
● So far, we’ve called methods on samBot, an instance of Robot
● Where did those classes come from?
● Next: how to use a class as a blueprint to actually build instances!
public class Robot {
Constructors (1/3)

● Robots can turnRight, moveForward,


etc. public void turnRight() {
// code that turns robot right
● Can call any of these methods on
}
any instance of Robot
● But how did these instances get public void moveForward(int numSteps) {
created in the first place? // code that moves Robot forward
}
● Define a special kind of method in the
Robot class: a constructor
/* other code */
● Note: every object must have a }
constructor
public class Robot {
Constructors (2/3)
public Robot () {
// this is the constructor!
}
● A constructor is a special kind of
method that is called whenever an public void turnRight() {
object is to be “born”, i.e., created – // code that turns robot right
see shortly how it is called }
● Constructor’s name is always the
public void moveForward(int numSteps) {
same as name of class
// code that moves Robot forward
● If the class is called “Robot”, its }
constructor needs to be called
“Robot”. If the class is called “Dog”, /* other code */
its constructor had better be called }
“Dog”
public class Robot {
Constructors (3/3)
public Robot () {
// this is the constructor!
● Constructors are special methods: }
used only once, to create the public void turnRight() {
instance // code that turns robot right
}
● And we never specify a return value
public void moveForward() {
in its declaration // code that moves Robot forward
}
● Constructor for Robot does not take
in any parameters (notice empty public void moveForward(int numSteps) {
parentheses) // code that moves Robot forward
}
● Constructors can, and often do, take
/* other code */
in parameters– later… }
Instantiating Objects (1/3)

● Now that the Robot class has a constructor, we can create


instances of Robot !
● Here’s how we create a Robot in Java:
new Robot();
● This means “use the Robot class as a blueprint to create a new
Robot instance”
● Robot() is a call to Robot’s constructor, so any code in the
constructor will be executed as soon as you create a Robot
Instantiating Objects (2/3)

● We refer to “creating” an object as instantiating it


● When we say:
new Robot();
● … We’re creating an instance of the Robot class, a.k.a.
instantiating a new Robot
● Where exactly does this code get executed?
Invoking Methods

• We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods
count = title.length()

• A method may return a value, which can be used in an assignment or expression


• A method invocation can be thought of as asking an object to perform a service
References

• Note that a primitive variable contains the value itself, but an object variable contains the address of the object
• An object reference can be thought of as a pointer to the location of the object
• Rather than dealing with arbitrary addresses, we often depict a reference graphically

num1 38

name1 "Steve Jobs"


Assignment Revisited

• The act of assignment takes a copy of a value and stores it in a variable


• For primitive types:

num1 38
Before:
num2 96

num2 = num1;

num1 38
After:
num2 38
Reference Assignment

• For object references, assignment copies the address:

name1 "Steve Jobs"


Before:
name2 "Steve Wozniak"

name2 = name1;

name1 "Steve Jobs"


After:
name2
Static Class Members

• A static method can be invoked through its class name


• For example, the methods of the Math class are static:
result = Math.sqrt(25)

• Variables can be static as well


• Determining if a method or variable should be static is an important design decision

6-64
The static Modifier

• We declare static methods and variables using the static modifier


• It associates the method or variable with the class rather than with an object of that class
• Static methods are sometimes called class methods and static variables are sometimes called class variables
• Let's carefully consider the implications of each

6-65
Static Variables

• Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists
public static float price;

• Memory space for a static variable is created when the class is first referenced
• All objects instantiated from the class share its static variables
• Changing the value of a static variable in one object changes it for all others

6-66
Static Methods

class Helper
{
`` private int hello=5;
public static int cube (int num)
{
Sys.out.println(this.hello)
;
return num * num * num;
}
} Because it is declared as static, the method
can be invoked as
value = Helper.cube(5);

6-67
Static Class Members

• The order of the modifiers can be interchanged, but by convention visibility modifiers come first
• Recall that the main method is static – it is invoked by the Java interpreter without creating an object
• Static methods cannot reference instance variables because instance variables don't exist until an object exists
• However, a static method can reference static variables or local variables

6-68
Static Class Members

• Static methods and static variables often work together


• The following example keeps track of how many objects have been created using a static variable, and makes that
information available using a static method

6-69
class MyClass {
private static int count = 0;

public MyClass () {
count++;
}
public static int getCount () {
return count;
}
}
-------------------------

MyClass obj;

for (int scan=1; scan <= 10; scan++)


obj = new MyClass();

System.out.println ("Objects created: " +


6-70 MyClass.getCount());
The this Reference

• The this reference allows an object to refer to itself


• That is, the this reference, used inside a method, refers to the object through which the method is being executed
• Suppose the this reference is used in a method called tryMe, which is invoked as follows:

obj1.tryMe();
obj2.tryMe();

• In the first invocation, the this reference refers to obj1; in the


second it refers to obj2

6-71
The this reference

• The this reference can be used to distinguish the instance variables of a class from corresponding method parameters
with the same names

• The constructor of the Account class (from Chapter 4) could have been written as follows:

public Account (Sring name, long acctNumber,


double balance)
{
this.name = name;
this.acctNumber = acctNumber;
this.balance = balance;
}

6-72
References

• Recall that an object reference holds the memory address of an object

• Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object

ChessPiece bishop1 = new ChessPiece();

bishop1

6-73
References

• Things you can do with a reference:

•Declare it : String st;


•Assign a new value to it
•st = new String(“java”);
•st2 = new String(“java”);

•st = st2;
•st = null;
•Interact with the object using “dot” operator : st.length()
•Check for equivalence
•(st == st2)
•(st == null)
6-74
The null Reference

• An object reference variable that does not currently point to an object is called a null reference
• The reserved word null can be used to explicitly set a null reference:
name = null;

or to check to see if a reference is currently null:

if (name == null)
System.out.println ("Invalid");

6-75
The null Reference

• An object reference variable declared at the class level (an instance variable) is automatically initialized to null
• The programmer must carefully ensure that an object reference variable refers to a valid object before it is used
• Attempting to follow a null reference causes a NullPointerException to be thrown

• Usually a compiler will check to see if a local variable is being used without being initialized

6-76
Method Overloading

• Method overloading is the process of giving a single method name multiple definitions
• If a method is overloaded, the method name is not sufficient to determine which method is being called
• The signature of each overloaded method must be unique
• The signature includes the number, type, and order of the parameters

6-77
Method Overloading

• The compiler determines which method is being invoked by analyzing the parameters

float tryMe(int x)
{ Invocation
return x + .375;
result = tryMe(25, 4.32)
}

float tryMe(int x, float y)


{
return x*y;
}

6-78
Method Overloading

• The println method is overloaded:

println (String s)
println (int i)
println (double d)
and so on...

• The following lines invoke different versions of the println method:

System.out.println ("The total is:");


System.out.println (total);

6-79
Overloading Methods

• The return type of the method is not part of the signature


• That is, overloaded methods cannot differ only by their return type
• Constructors can be overloaded
• Overloaded constructors provide multiple ways to initialize a new object

6-80
Overloading Methods

• Constructors can be overloaded

• An overloaded constructor provides multiple ways to set up a new object

6-81

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy