Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming Basics:

Similar presentations


Presentation on theme: "Object Oriented Programming Basics:"— Presentation transcript:

1 Object Oriented Programming Basics:
Tirgul 3 Object Oriented Programming Basics: Classes, objects 1

2 Up until now Procedural programming
Got us to think of procedures as the basic building blocks. Compose complex procedures from simple ones. Fits naturally with human thinking e.g. How to get to work: Get into car Start car Put car in first gear

3 Thinking in “Objects” Objects try to integrate another human concept into computer programs: The notion of State. Objects are a combination of state, and actions that relate to that state or change it. Objects may represent physical things (Car, Person) or abstract things (Position, Vector).

4 Example: Car Let’s think of a car It has a state
are the doors open? Is it on? is the hand break up? How much fuel does it have? Actions on it depend on its state: Trying to turn the car on when there is no fuel Turning on the radio without keys in the ignition Hitting the breaks

5 Car Example (Cont.) There are combinations of states & actions that we want to avoid: Put the car in reverse while driving 100 kph Leave the lights on when the car is off Different cars behave similarly At a given time, may have different states But the rules are the same Instances of the same class

6 How would it look like in Java?
public class Car { private double _fuel; private int _currentGear; private boolean _radioOn; ... public void fillUpFuel(double fuel){...} public boolean isRadioOn(){...} public void turnOn(){...{ } Fields. Represent state. Methods. Allow to change state, interact with the object.

7 The API of the class The Application Program Interface (API) is our “gateway” for interacting with the class. It is the set of public methods and members that we can use when we interact with it. It hides away a lot of the internal workings (on purpose). It is a contract – an exact behavior the class promises to uphold.

8 Javadoc Javadoc is a JDK tool that converts the public documentation to nicely formatted html pages – that document the API You are required to document ALL methods and fields (public and private) using Javadoc. starting from ex3! Only the public methods and members will appear in the API. Javadoc comments appear between /** and */ Examples will follow…

9 Simple class example - Position
A position in a two-dimensional world is a pair of coordinates: (x,y) We’ll use this simple concept as an example for a simple class-object- instance case. The attributes of a position are: int to represent the x coordinate, and int to represent the y coordinate. We need to be able to create a position, otherwise the “position” class is useless. (constructor) We would also like to be able to get the X and Y values of a position. (methods) For the time being, a position is fixed and we don’t want to change it after creation.

10 Position – fields public class Position{ private int _x; private int _y; … The members are declared private. Only methods of the class can access them and change them. The class itself is declared using the public modifier which means the class has a public API. The class is accessible to everyone.

11 Class Position Javadoc documentation for the class
/** *this class implements an X,Y coordinate *position on a grid. Introcsp */ public class Position{ /** * The x coordinate. */ private int _x; * The y coordinate. private int _y; ... } Javadoc documentation for the class documentation for fields

12 Constructor for the class
Class Position - Constructor /** *construct a position given x,y coordinates x the X coordinate. y the y coordinate. */ public Position(int x, int y){ _x = x; _y = y; } Constructor for the class The constructor initializes the fields. It is declared public so that anyone can create instances of this class.

13 Constructors – Summary
Constructors are special types of methods. They run when the instance is created. Usually declared public. They have the same name as the class. The constructor is the only method with no specification of return type (int, double, void, etc.) public <ClassName> (<params>) {…}

14 Class Position /** *return the x coordinate the x coordinate. */ public int getX(){ return _x; } /** ... */ public int getY(){…} The method are declared public to enable access from outside the class. getX() and getY() let you view the private fields Still, you cannot change the fields after creation.

15 Naming conventions Class name begins with a capital letter.
Class fields are indicated by the _ prefix. Method names written with regular letters and capital letters separating the different words in the name getX(), chooseWorld(), turnLeft() etc. Constants are indicated by capital letters separated by _ : STEPS_IN_MILE.

16 Reserved word – creates a new instance
Position instantiation Position pos = new Position(7,4); This will create an instance of a Position with the coordinates 7 and 4 for x and y in respect. The identifier name is pos. The left hand-side Position and the right hand side Position do not have the same meaning! The 1st is a type, the 2nd is a method call Reserved word – creates a new instance Type declaration Constructor call

17 Creating Instances We create some instances of Position inside the main() and work with them public static void main(String[] args){ Position p1 = new Position(1,1); Position p2 = new Position(1,1); if (p2 == p1){ System.out.println(“the two objects are identical”); } else{ System.out.println(“the two objects are not identical”); } if (p2.getX()==p1.getX() && p2.getY()==p1.getY()){ System.out.println(“the two objects are similar”); } else{ System.out.println(“the two objects are not similar”); } }

18 These observations are VERY important
Output the two objects are not identical the two objects are similar pos and position are two different objects! We say that they are two different instances of the same class. Though, their members are the same. These observations are VERY important

19 Adding Constructors Here’s an example of another constructor.
It copies the fields from a different position object. /** * A copy constructor. other the position object to copy. */ public Position(Position other){ _x = other._x; _y = other._y; } Notice how one object can access the private fields of another. This is because they are in the same class.

20 Overloading How can we have two constructors?
Which one is called? The compiler decides according to the number and type of arguments. Position p1 = new Position(10,3); Position p2 = new Position(p1); Overloading is also possible with methods. You must make sure that the methods signature (number and types of parameters) is different.

21 Adding more methods to Position
We can add more useful methods to Position to make it easier to use. For example: public int distanceFrom(Position other){ return Math.abs(_x-other._x)+ Math.abs(_y-other._y); } public Position halfWayTo(Position other){ return new Position((_x + other._x)/2, (_y + other._y)/2); And so on… Manhattan distance to another position Get a position object approximately in between two others.

22 Prototype of a simple robot
Imagine we want to design a robot that will be able to move in the world, find and carry things (beepers, maybe?), collect or place them in different places. We might want the robot to have a name. We might want the robot to perform complicated tasks (sabotage antennas?).

23 Karel - Object Oriented
We will call the prototype of our primitive robot MyKarel. The prototype is defined in a Class . Karel’s attributes: Name Position in the world (what world? What does position mean?) Orientation Bag of beepers

24 What can Karel do? Be created (born) Move: Turn: Pick a beeper
Forward Backward (?) Turn: Right Left backward Pick a beeper Put a beeper Die Tell us its position Tell us its orientation Check if the front and sides are clear etc.

25 Warning! The following slides do not represent the full-real implementation of Karel and other relevant classes. The slides should serve as an example for the concept of Object Oriented Programming (OOP).

26 Attributes (fields/members)
MyKarel Class /** * This class implements a basic robot */ public class MyKarel { private String _name; private int _orientation; private Position _position; private int _beepersInBag; … } MyKarel and not Karel since it’s a new and different class Attributes (fields/members)

27 Don’t hesitate to define new constants when you need them…
Orientation?! /** *… */ public class MyKarel { /**signifies the east orientation*/ public static final int EAST = 1; /**signifies the north orientation*/ public static final int NORTH = 2; /**signifies the west orientation*/ public static final int WEST = 3; /**signifies the south orientation*/ public static final int SOUTH = 4; … private String _name; … } Don’t hesitate to define new constants when you need them… The constants are static since they are shared between all instances of this class

28 Position? Position is the robot’s position in the world.
Our world is a grid with borders and (maybe) inner walls. The position of a robot is its X and Y coordinates. Why not use our already existing class within Karel?

29 Class as a variable type
private Position _position; The private member _position is of Position type: we use simpler classes as the building blocks for more complicated classes. This is yet another aspect of top-down design

30 MyKarel – constructor(1)
/** *constructs a robot standing at the origin, *with north orientation and no beepers in bag name the robot’s name. */ public MyKarel(String name){ _name = name; _orientation = NORTH; _position = new Position(1,1); _beppersInBag = 0; }

31 MyKarel – constructor(2)
/** *constructs a robot with name, orientation, position and * num of beepers in bag given as parameters. name the robot’s name. orientation the robot’s initial orientaion pos the robot’s initial position beepersInBag the number of beepers in bag */ public MyKarel(String name, int orientation, Position pos, int beepersInBag){ _name = name; _orientation = orientation; _position = pos; _beppersInBag = numofBeepers; }

32 Default Constructor In case no constructor was defined - the Java compiler creates a default constructor with no parameters. the compiler-created constructor can be dangerous – it assigns 0 to numeric members, false to booleans and null to objects. null is a special value indicating an “empty object”

33 MyKarel – move() public Position move(){ int x = _position.getX(); int y = _position.getY(); switch(_orientation){ case EAST: _position = new Position(x+1,y); break; case NORTH:_position = new Position(x,y+1); break; case WEST: _position = new Position(x-1,y); break; case SOUTH: _position = new Position(x,y-1); break; default: break; } return _position; } We don’t perform any world boundaries/walls check. It might be a problem

34 MyKarel – turnLeft() Notice the direct access to _orientation.
public void turnLeft(){ switch(_orientation){ case EAST: _orientation = NORTH;break; caseNORTH: _orientation = WEST;break; case WEST: _orientation = SOUTH;break; case SOUTH: _orientation = EAST;break; default: break; } } Notice the direct access to _orientation. This is possible since turnLeft() is part of MyKarel class. The implementation of turnRight() is similar.

35 MyKarel – turnBack() We can implement turnBack() in a few ways:
public void turnBack(){ turnLeft(); turnLeft(); } Or (but not together): public void turnBack(){ turnRight(); turnRight(); We can also simply change orientation with switch-case

36 When would we use private methods in MyKarel?
To break up long public methods into simpler pieces To avoid code repetitions between different public methods Example: public MyKarel(String name){ initBeeperBag(); ... } private void initBeeperBag(){...}

37 Other methods and classes
In the implementation of the real Karel there are more classes and methods: KarelWorld – the class represent a prototype Karel’s world. It’s capable of drawing itself, adding/removing robots and of drawing the robots actions (pick, put, move, turn). The KarelWorld class uses some other useful java classes.

38 The Keyword this Sometime you may want to pass the current object as an argument to a method, or return it as a return value. They keyword this refers to the current object. Example: let’s assume the class KarelWorld has a method that registers robots: public void addRobot(MyKarel robot) We want to register every robot that is created – we can do this in the constructor of MyKarel!

39 Example for using this public MyKarel(String name, KarelWorld world){ ... world.addRobot(this); } Another possible use is to access methods or fields using this (It is sometimes clearer to read): this._x = other._x; Which is equivalent to: _x = other._x;

40 Encapsulation The user doesn’t care and shouldn’t be aware of implementation details. It doesn’t matter whether turnBack() is implemented this way or another as long as it obeys the API specifications. We can change the implementation of the class and it will still work with programs that use the interface

41 Encapsulation cont. This separation between the public interface (API) and the actual implementation is called encapsulation. The object internals are hidden and we can only access/see/use the interface. The implementation details are black-box.

42 What is this orientation?
Encapsulation is safer: There are some things we don’t want people to do with Karel: MyKarel karel = new MyKarel(“karel”); karel._position = new Position(10,300); karel._orientation = 53; To avoid these problems, we block access to some methods and fields (make them private). E.g. Karel can only rotate via a method that makes sure the value of _orientation stays legal. Teleporting Karel? What is this orientation?

43 Encapsulation is Safer
Encapsulating implementation details is not meant to be secure against attacks (e.g. hackers that want to make Karel teleport) It is supposed to protect us as the programmers from accidentally doing damage. The compiler doesn’t let you access private fields just like it does not allow you to assign a double into an int without casting. These compiler warnings are ways to let you know you did something that is probably wrong.

44 To summarize: Encapsulation
Helps in breaking down the problem to independent pieces Allows many programmers to work simultaneously on one large project Protects the program from misuse by only allowing access through carefully designed methods Object implementation can be modified without modifying the “client” application

45 Static Methods and Variables

46 The main function structure
public static void main(String[] args){ … } void – since the main doesn’t return any argument or value. public – the main method accessible to all. static – the main method can be called without creating an instance of the MyTester class first.

47 Static methods/variables
Recall the constants declarations: public static final int EAST = 1; We could also have static methods: public static void printInfo() {…} public static double sin(double angle){…} These values and methods do not require an instance of their class in order to access/use them As opposed to “instance methods” which require an instance construction before use.

48 Static variables Static variables can be accessed without instantiation of a class object. They do not have to be final (Not all of them are constants). All instances “share” a single static variable. It belongs to the entire class. We define constants as static to conserve memory. (No need for a different copy every time)

49 Example for the use of static: give each object a unique ID.
_nextID will hold the id we are about to give public class Robot { private static int _nextId = 0; private final int _id; public Robot(){ _id = _nextId; _nextId++; } ... Notice how _id is final. It will never be changed to an illegal value. Every time the constructor is called, a new id is given out.

50 Static methods Static methods use no instance variables of any object of the class they are defined in. They may use static variables. This is typical of methods which do some kind of generic calculation (or generic print). Examples: Math.sin() System.out.println() MyKarel.printUsageIntructions()

51 The main method At runtime - execution starts with the main method. (We have no objects yet!) A class doesn’t necessarily have a main method. A program MUST have one. Usually a set of classes constitutes a program. Only one main is needed. Calling ‘java MyClass’ will run the main of MyClass even if other classes have main of their owns In your home assignments the main is sometimes written by us (the TAs) and serves us to test your programs (hence a tester file or a driver file). The main can be in a different separated class

52 Static – Do and Don’t do public class StaticExample {
public StaticExemple() {} //ctor public static void myStaticMethod() {} //static method public void myNonStaticMethod() {} //non-static method public static void main(String[] argv) { //static as always myStaticMethod(); //OK myNonStaticMethod(); //compilation error StaticExample ex = new StaticExample(); //instantiation ex.myStaticMethod(); //OK though ‘ex’ can be removed ex.myNonStaticMethod() //OK }

53 Static – Do and Don’t do (2)
myNonStaticMethod() call is wrong since a static method (main) cannot call a non-static one A non-static method is “attached” to an object But which object's myNonStaticMethod() should be invoked? StaticExample class might have many instances (objects) ... Choose carefully which methods will be static and which will not!

54 Static – Do and Don’t do (3)
A static method (main) can invoke a static method too on a specific instance (ex.myStaticMethod()) Invoking a static method on an object is translated into invoking that static method on its class.


Download ppt "Object Oriented Programming Basics:"

Similar presentations


Ads by Google