Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming Introduction to Classes and Objects.

Similar presentations


Presentation on theme: "Object Oriented Programming Introduction to Classes and Objects."— Presentation transcript:

1 Object Oriented Programming Introduction to Classes and Objects

2 The Procedural Programming Approach Procedural programming involves – choosing data structures, – designing algorithms and – translating algorithms into codes In procedural programming data and operations on data are different This means that in procedural programming, data is always sent to the procedures and functions that manipulate the data This approach presents many challenges to program development

3 Introduction to OOP OOP combines procedural language programming with added dimensions that provide more flexibility, modularity, clarity and reusability through – class encapsulation, – class inheritance and – polymorphism In OOP data and operations pertaining to data are placed within a single entity known as object This approach addresses many of the challenges in procedural programming languages In OOP, the programs are designed to reflect real world objects Objects are associated with both attributes and activities Using objects improves software reusability and makes software development much easier

4 Defining Classes for Objects OOP involves programming using objects An object represents anything in the world that can be distinctly identified Examples are a computer, a student, a table, a book and even an event such as graduation ceremony An object has distinct identity, state and behaviour The state of an object consists of its data field (known as properties) with their current values The behaviour of an object is defined by a set of methods Invoking a method on an object is like asking the object to perform some task

5 Classes and Objects A rectangle object has data field members length, breadth and height which characterise every rectangle Classes are therefore the templates or the formats that define objects of some type A class is a blueprint or a general template that defines the data and methods for an object In Java, variables are used to define the data fields, and methods are used to define behaviours In addition, a class provides special methods known as constructors Constructors of a class are invoked to construct objects of the class Like methods, constructors can perform any action, but are defined to specifically initialise object data fields

6 A Car Class public class Car { String regNumber; // e.g. Registration number double speed; // in kilometres per hour double maxSpeed; // in kilometres per hour } These variables (regNumber, speed and maxSpeed) are called the member variables, instance variables, or fields of the class. Fields tell you what a class is and what its properties are. An object is a specific instance of a class with particular values for the fields. While a class is a general blueprint for objects, an instance is a particular object.

7 Constructing Objects with new class Car { String regNumber; double speed; double maxSpeed; } To create an object in Java, we use the keyword new followed by a call to the class's constructor. Here's how we create a new Car variable called car1: Car car1; car1 = new Car();

8 Using Constructors Constructors are special kind of methods with the following characteristics – Constructors must have the same name as the defining class – Constructors do not have return types – not even void – Constructors are invoked using the new operator to create objects of the class – Constructors are mainly used for initialising objects A constructor can be overloaded to construct objects with different initial data values To construct an object from a class the constructor is invoked using the new operator The general syntax for a constructor is given by new ClassName( argument );

9 Constructing Objects The first word, Car, declares the type of the variable car1. Classes are types and variables of a class type need to be declared just like variables of primitive types such as ints or doubles. The equals sign is the assignment operator and new is the construction operator. Finally the parentheses around Car() tell you this is a method and not a data type like the Car on the left hand side of the assignment. This is a constructor, a method that creates a new instance of a class. More on constructors shortly.

10 Constructing Objects continued If not explicitly declared the compiler inserts a default constructor that takes no arguments. The default constructor can be used in instantiation of various objects of the class This is often condensed into one statement as the following examples: Different objects can be instantiated as follows: Car car1 = new Car(); Car car2 = new Car();

11 Constructor When a class is defined, the class would generally have a constructor that has no arguments Such constructors are known as no-arg or no- argument constructors The no-arg constructors are implicitly declared in the class and have empty body This constructor is known as default constructor The default constructors are provided automatically if no constructors are explicitly declared in the class Note that constructors have no return type, not even void

12 Instantiation A class is a blue print that defines the data and methods for an object An object is an instance of a class There can be many instances of a class Creating an instance is referred to as instantiation The terms objects and instance are used interchangeably The relationship between a class and its object can be likened to a building plan and the building itself One building plan can be used to construct many other buildings

13 Using an Object in a Different Class public class Car { String regNumber; double speed; double maxSpeed; } class CarApp { public static void main( String[ ] args ) { Car car1 = new Car(); car1.regNumber = “GW 3835 X”; car1.speed = 65.0; car1.maxSpeed = 110.45; System.out.println(car1.regNumber + “ is travelling at ” + car1.speed + “ kilometres per hour. ” ); }

14 Using an Object in a Different Class The program requires not just the CarApp class but also the Car class. To make them work together we put the Car class in a file called Car.java. We also put the CarApp class in a file called CarApp.java. We need to put both these files in the same directory and compile both files in the usual way. We can finally run CarApp. For example, we compile by typing javac Car.java javac CarApp.java java CarApp The output is GW 3835 X is travelling at 65.0 kilometres per hour. Note that the Car class does not have a main() method so we cannot run it. It can exist only when called by other programs that do have main() methods.

15 Multiple Class Applications Many of the applications we shall write from now on will use multiple classes. It is customary in Java to put every class in its own file. Very soon, we will learn how to use packages to organize our commonly used classes in different directories. For now we will keep all our.java source code and.class byte code files in one directory.

16 Initialising Fields (Class Variables) Fields can (and should often) be initialised when they are declared, just like local variables. class CarMod { String regNumber = “”; double speed = 0.0; double maxSpeed = 110.; } The next program creates a new car and prints it:

17 Creating A Car Object class CarModApp { public static void main( String[ ] args ) { CarMod car = new CarMod(); System.out.println( car.regNumber + “ is travelling at ” + car.speed + “ kilometres per hour. ” ); }

18 The Circle class Definition public class Circle { // the radius of this circle double radius; // Constructing a Circle object Circle( ) { } // Constructing a circle object with a specified radius Circle( double circleRadius ) { radius = circleRadius; }

19 The Circle Class // return the area of this circle double circleArea() { return 3.14159 * radius * radius; } Note that the Circle class defined above is different from all the classes we have defined so far There is no main method in the Circle class so it is not possible to run it It is a mere definition for creating a circle of any size

20 Classes Have Methods Data types are not much useful unless they can perform certain actions For this purpose classes have methods. Fields say what a class is. Methods say what a class does. The fields and methods of a class are collectively referred to as the members of the class. The classes we have seen so far have mostly had a single method, main(). However, in general, classes can have many different methods that do many different things. For instance the Car class might have a method to make the car go as fast as it can.

21 The Car Class with Method class CarMod1 { String regNumber = “”; double speed = 0.0; double maxSpeed = 110.0; // accelerate to maximum speed // press the pedal to touch the metal void pressDown() { this.speed = this.maxSpeed; }

22 Car class with a method The fields are the same as before, but now there is also a method called pressDown(). It begins with the Java keyword void which is the return type of the method. Every method must have a return type which will either be void or some data type like int, byte, float, or String. The return type specifies the kind of value that will be sent back to the calling method when all calculations inside the method are completed. If the return type is int, for example, the method can be used anywhere an int constant is used. If the return type is void then no value will be returned. The name of the method is pressDown. As usual the name is followed by two empty parentheses.

23 Class with method Any arguments passed to the method would be passed between the parentheses, but this method has no arguments. Note that there is one statement inside the method this.speed = this.maxSpeed; Notice that within the Car class the field names are prefixed with the keyword this to indicate that we are referring to fields in the current object. Like all methods the body of the pressDown() method is enclosed in { and } and within the class.

24 Invoking a Method class CarMod2 { String regNumber = “”; // e.g. “GW 3835 X” double speed = 0.0; // in kilometres per hour double maxSpeed = 110.0; // in kilometres per hour // to accelerate to maximum speed // press the pedal to touch the metal void pressDown() { this.speed = this.maxSpeed; }

25 Invoking the method Outside the Car class, we can call the pressDown() method just like we reference fields Using the name of the object you want to accelerate to maximum and the. separator as demonstrated below

26 class CarApp3 { public static void main(String[ ] args ) { CarMod2 car3 = new CarMod2(); car3.regNumber = “GS 3638 Y”; car3.maxSpeed = 110.0; System.out.println(car3.regNumber + “ is travelling at ” + car3.speed + “ kilometres per hour. ”); car3.pressDown(); System.out.println(car3.regNumber + “ is travelling at ” + car3.speed + “ kilometres per hour. ”); }

27 The Implied this Object Within the Car class, we do not absolutely need to prefix the field names with this as in this.regNumber or this.speed. Just regNumber and speed are sufficient. The this may be implied. That is because the pressDown() method must be called by a specific instance of the Car class, and this instance knows what its data is. Another way of looking at it is that, every object has its own copy of the pressDown() method. For clarity, we will use an explicit this for now, and I recommend you do so too, at least initially. As we become more comfortable with Java, classes, references, and OOP, we will be able to leave out the this without fear of confusion. Most real-world codes do not use an explicit this.

28 Accessing Objects By Reference Variables Objects are accessed by means of object reference variables Object reference variables contain references to the object Object reference variables can be declared using the general syntax ClassName objRefVar; Generally, a class is used to define a type known as reference type Every class defined represents a type – each time a new class is defined a new type is also created Any variable of a class type can reference to an instance of the class

29 Reference Types The following statement defines a variable of the Circle type Circle smallCircle; The variable smallCircle can reference a Circle object The following statement creates an object and assigns its reference to smallCircle smallCircle = new Circle(); The above two step declaration can be written in a single statement using the general syntax below ClassName objRefVar = new ClassName(); An example is Circle smallCircle = new Circle();

30 Accessing an Object’s Data and Methods When an object is created its data and methods can be accessed using the dot operation The general syntax for referencing an objects data is given as theObject.itsData //this references and object’s data The general syntax for referencing an object’s method is given as theObject.itsMethod( arguments ) //this references and object’s data For example, someCar.speed references the speed of the object someCar Also someCar.stop() invokes the stop method of someCar object In the above examples, the data field speed is an instance variable because it depends on a specific instance For the same reason, the method stop() is an instance method because it can be invoked on specific instances

31 Null the Reference Default Value If a reference variable does not reference any object the variable holds a special value in Java called null The term null is just a literal word as true and false Just as true and false are boolean literals, null is for reference type variables The default values for data fields for reference type variables is null, 0 for numeric type, and false for boolean type However, Java assigns no default values to local variables inside a method An object must be created before referencing it through a reference variable

32 Primitive Verses Reference Variable Every variable represents a memory location for holding data values When a variable is declared it tells the compiler the type of value the variable will hold Primitive type of variables hold primitive values Reference type of variables hold values that are references to where objects are stored in memory locations When one variable is set to another variable the variable is set to the same value For primitive data types the real value of the variable is assigned to the value of the other variable For reference variables, the reference of one variable is assigned to the other variable

33 Variable Types Consider the two primitive variables var1 and var2 If the value of var2 is assigned to var1 as in var1 = var2 ; In the above expression the content value of var2 will be copied into the value of var1 Consider also the two reference variables ref1 and ref2 If ref2 is assigned to ref1, as ref1 = ref2, the reference of ref2 is copied into the reference of ref1 The two reference variables reference the same object After the assignment statement the object referenced by ref1 is no longer useful, and becomes garbage

34 Java Access Modifiers In Java, there are different modifiers that control access to data, methods and classes Some commonly used access modifiers are public, private and default packaged-access The public access makes classes, methods and data fields accessible from any class The private access makes methods and data fields accessible only from within its own class If public or private is not specified, then by default the classes, methods and data fields are accessible by any class in the same package This is known as package access or package-private If a class is not declared public it can only be accessed within the same package

35 public class Klass1 { public int p; //unrestricted int q; // package restricted private int r; //class restricted public void method1() { } void method2() { } private void method3() { } public class Klass2 { Klass1 obj = new Klass1(); obj.p; //can access p obj.q;//can access q obj.r; //cannot access r obj.method1(); //can invoke method1 obj.method2(); //can invoke method2 obj.method3(); //cannot invoke method3 } The private modifier restricts access to within a class; the default modifier restricts access to within a package; and the public enables unrestricted access

36 Data Encapsulation It is not a good practice to allow direct modification of class’s data fields by object references Direct modification makes the class difficult to maintain and vulnerable to bugs To prevent direct modification of class data fields by object references, data fields are declared as private This is known as data field encapsulation Private data fields cannot be accessed by objects through direct referencing from outside the class that defines the private field Clients often need access to data fields for manipulation

37 Accessing Data Fields To make private data fields accessible, the class provides public get methods that return the value of the data To enable private data fields to be modified the class provides public set methods to set them to new values The general signature for get methods is public returnType getFieldName() If the get method is a boolean type the get method is defined as public boolean isFieldName() The set methods have the signature public void setFieldName( dataType fieldValue )

38 Data Access Until now all the programs we have seen are quite simple in structure. Each program was contained in exactly one class. This class had a single method, main(), which contained all the program logic and variables. The variables in those classes were all local to the main() method. They could not be accessed by anything outside the main() method. These are called local variables. Everything the program needs to run is contained inside a single method. It's quite an efficient arrangement for small programs It will break down when you want to design something bigger or more complex.

39 Member Variables and Local Variables class CarMod3 { String regNumber = “”; // member variable double speed = 0.0; // member variable double maxSpeed = 110.0; // member variable boolean isSpeeding() { double excess; // local variable excess = this.maxSpeed - this.speed; if ( excess < 0 ) return true; else return false; }

40 Member and Local Variables The regNumber, speed and maxSpeed variables of the Car class, however, belong to Car object, not to any individual method. They are defined outside of any methods but inside the class and are used in different methods. They are called member variables or fields. Member variable, instance variable, and field are different words that mean the same thing. Field is the preferred term in Java. Member variable is the preferred term in C++.

41 Passing Arguments to Methods It's generally considered bad programming practice to access fields directly. Instead it is considered good object oriented practice to access the fields only through methods. This allows programmers to change the implementation of a class without changing its interface. This also allows the enforcement of constraints on the values of the fields. To do this we need to be able to send information into the Car class. This is done by passing arguments to methods.

42 Arguments to Methods For example, to allow other objects to change the value of the speed field in a Car object, the Car class could provide an accelerate() method. This method does not allow t he car to exceed its maximum speed, or to go slower than 0 kph.

43

44

45


Download ppt "Object Oriented Programming Introduction to Classes and Objects."

Similar presentations


Ads by Google