Download presentation
Presentation is loading. Please wait.
Published byOlivia Ryan Modified over 8 years ago
1
Dr. Majed Abdouli © 2015. Objects and Classes 1 Dr. Majed Abdouli © 2015, adapted from Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
2
Dr. Majed Abdouli © 2015. Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it? 2
3
Dr. Majed Abdouli © 2015. Objectives To describe objects and classes, and use classes to model objects (§8.2). To use UML graphical notations to describe classes and objects (§8.2). To demonstrate defining classes and creating objects (§8.3). To create objects using constructors (§8.4). To access objects via object reference variables (§8.5). To define a reference variable using a reference type (§8.5.1). To access an object’s data and methods using the object member access operator (.) (§8.5.2). To define data fields of reference types and assign default values for an object’s data fields (§8.5.3). To distinguish between instance and static variables and methods (§8.7). To define private data fields with appropriate get and set methods (§8.8). To encapsulate data fields to make classes easy to maintain (§8.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (§8.10). 3
4
Dr. Majed Abdouli © 2015. 4 OO Programming Concepts Object-oriented programming (OOP) involves programming using Classes and Objects. A class is used to describe something in the world, such as occurrences, things, external entities, roles, organization units, places or structures. It is often described as a template, generalized description, pattern or blueprint for an object, as opposed to the actual object, itself.
5
Dr. Majed Abdouli © 2015. 5 Once a class of items is defined, a specific instance of the class can be defined. An instance is also called “object”. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods, in other words what the object does. In other words an object is a software bundle of variables and related methods.
6
Dr. Majed Abdouli © 2015. 6 The table gives some examples of classes and objects Class and Object Example
7
Dr. Majed Abdouli © 2015. 7 UML Class and Object Diagrams: A class diagram is simply a rectangle divided into three compartments. The topmost compartment contains the name of the class. The middle compartment contains a list of attributes (member variables), and the bottom compartment contains a list of methods (member functions). The purpose of a class diagram is to show the classes within a model.
8
Dr. Majed Abdouli © 2015. 8 Kinds of classes: Standard Class: Don’t reinvent the wheel. When there are existing classes that satisfy our needs, use them. Learning how to use standard Java classes is the first step toward mastering OOP. Some of the standard classes are JOptionPane, String, Scanner etc Programmer defined Class: Using just the String, JOptionPane, Scanner, JFrame and other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. Classes we define ourselves are called programmer-defined classes
9
Dr. Majed Abdouli © 2015. 9 class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor)
10
Dr. Majed Abdouli © 2015. Example of a Class 10
11
Dr. Majed Abdouli © 2015. Object Declaration 11 More Examples Student jan; Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated. Class Name This class must be defined before this declaration can be stated. Accountcustomer; Studentjan, jim, jon; Vehiclecar1, car2;
12
Dr. Majed Abdouli © 2015. Object Instantiation 12 jan = new Student ( ) ; More Examples Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here. customer = new Account(); jon= new Student(“John Java”); car1= new Vehicle( );
13
Dr. Majed Abdouli © 2015. Declaration vs. Instantiation 13 Student hussain; hussain = new Student( ); Student hussain; hussain = new Student( ); 1. The identifier hussain is declared and space is allocated in memory. 2. A Student object is instantiated and the identifier hussain is set to refer to it. 1 2 hussain 1 : Student 2 Declaration and Creation in one step Student hussain= new Student(); Create an object Assign object reference
14
Dr. Majed Abdouli © 2015. 14 Accessing members of a class. (dot) operator is used to access public members of a class A general syntax to access public members of a class is as follows // s is object of Student class Student s= new Student(); F Referencing the object’s data: objectRefVar.data e.g., s.name=“Ali”; // accessing public data member F Invoking the object’s method: objectRefVar.methodName(arguments) e.g., s.setName(“Ahmad”); // accessing method s.getName(); // accessing method
15
Dr. Majed Abdouli © 2015. Example 1: Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. 15 //student class definition class Student { /** name is a data member to store name of a student */ String name ; /** Methods of Student class */ public void setName(String n) { name=n; } Public String getName(){ return name; } } //Test class Teststudent definition class TestStudent { public static void main (String [] args) { // Creating object Student s = new Student (); s.name=“Ali”; System.out.println(“Name:” + s.name); s.setName(“Ahmad”); System.out.println(“Name:” + s.getName()); }
16
Dr. Majed Abdouli © 2015. Constructors 16 The constructor method is like a normal public method except that it shares the same name as the class and it has no return value not even void since constructors never return a value. It can have none, one or many parameters. Constructors are a special kind of methods that are invoked to construct objects. Normally for a constructor method to be useful we would design it so that it expects parameters. The values passed through these parameters can be used to set the values of the private fields.
17
Dr. Majed Abdouli © 2015. Constructors, cont. 17 A constructor with no parameters is referred to as a no-arg constructor. Point to be noted about constructor. 1.Constructors must have the same name as the class itself. 2.Constructors do not have a return type—not even void. 3.Constructors are invoked (called) using the new operator when an object is created. 4.Constructors play the role of initializing objects.
18
Dr. Majed Abdouli © 2015. Default Constructor 18 A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.
19
Dr. Majed Abdouli © 2015. 19 class Account { String ownerName; double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public Account(String name ) { ownerName = name; balance = 0.0; } public Account(String name, double b) { ownerName = name; balance = b; } Example 3: Defining Classes with constructors and Creating Objects. class TestAccount{ /* This sample program uses both the Bicycle and Account classes */ public static void main(String[] args) { Account acct, acct1, acct2; String myName = "Jon Java"; acct = new Account( ); acc1 = new Account(myName ); acct2 = new Account(“Ahmed”, 50); System.out.Println(acct.ownerName + acct.balance); System.out.Println(acct1.ownerName + acct1.balance); System.out.Println(acct2.ownerName + acct2.balance); }
20
Dr. Majed Abdouli © 2015. 20 Trace Code
21
Dr. Majed Abdouli © 2015. Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. 21 public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }
22
Dr. Majed Abdouli © 2015. Differences between Variables of Primitive Data Types and Object Types 22
23
Dr. Majed Abdouli © 2015. Copying Variables of Primitive Data Types and Object Types 23
24
Dr. Majed Abdouli © 2015. Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM. 24
25
Dr. Majed Abdouli © 2015. Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable. 25
26
Dr. Majed Abdouli © 2015. Instance Variables, and Methods 26 Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
27
Dr. Majed Abdouli © 2015. Static Variables, Constants, and Methods 27 Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.
28
Dr. Majed Abdouli © 2015. Static Variables, Constants, and Methods, cont. 28 To declare static variables, constants, and methods, use the static modifier.
29
Dr. Majed Abdouli © 2015. Static Variables, Constants, and Methods, cont. 29
30
Dr. Majed Abdouli © 2015. Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. 30 public class Circle2 { double radius; /** The radius of the circle */ static int numberOfObjects = 0; /** No of objects created */ /** Construct a circle with radius 1 */ Circle2() { radius = 1.0; numberOfObjects++; } /** Construct a circle with a specified radius */ Circle2(double newRadius) { radius = newRadius; numberOfObjects++; } /** Return numberOfObjects */ static int getNumberOfObjects() { return numberOfObjects; } /** Return the area of this circle */ double getArea() { return radius * radius * Math.PI; } }
31
Dr. Majed Abdouli © 2015. 31 public class TestCircle2 { /** Main method */ public static void main(String[] args) { System.out.println("Before creating objects"); System.out.println("The number of Circle objects is " + Circle2.numberOfObjects); // Create c1 Circle2 c1 = new Circle2(); // Display c1 BEFORE c2 is created System.out.println("\nAfter creating c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberOfObjects + ")"); // Create c2 Circle2 c2 = new Circle2(5); // Modify c1 c1.radius = 9; // Display c1 and c2 AFTER c2 was created System.out.println("\nAfter creating c2 and modifying c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberOfObjects + ")"); System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + c2.numberOfObjects + ")"); } }
32
Dr. Majed Abdouli © 2015. Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package. 32 F public The class, data, or method is visible to any class in any package. F private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.
33
Dr. Majed Abdouli © 2015. 33 Accessibility Example class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientService
34
Dr. Majed Abdouli © 2015. Why Data Fields Should Be private? To protect data. To make class easy to maintain. Internal details of a class are declared private and hidden from the clients. This is information hiding. 34
35
Dr. Majed Abdouli © 2015. Example of Data Field Encapsulation 35
36
Dr. Majed Abdouli © 2015. Recapitulation Specificity of Java and compilation steps Classes vs. Object Declaration and Instantiation Constructors Passing parameters by reference vs. value Static variables and methods Java Garbage Collector Private vs. public variables/methods 36
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.