Which of the following determines whether an object is an instance of a class?
Why OOP?Suppose that you want to assemble your own PC, you go to a hardware store and pick up a motherboard, a processor, some RAMs, a hard disk, a casing, a power supply, and put them together. You turn on the power, and the PC runs. You need not worry whether the motherboard is a 4-layer or 6-layer board, whether the hard disk has 4 or 6 plates; 3 inches or 5 inches in diameter, whether the RAM is made in Japan or Korea, and so on. You simply put the hardware components together and expect the machine to run. Of course, you have to make sure that you have the correct interfaces, i.e., you pick an IDE hard disk rather than a SCSI hard disk, if your motherboard supports only IDE; you have to select RAMs with the correct speed rating, and so on. Nevertheless, it is not difficult to set up a machine from hardware components. Show
Similarly, a car is assembled from parts and components, such as chassis, doors, engine, wheels, brake, and transmission. The components are reusable, e.g., a wheel can be used in many cars (of the same specifications). Hardware, such as computers and cars, are assembled from parts, which are reusable components. How about software? Can you "assemble" a software application by picking a routine here, a routine there, and expect the program to run? The answer is obviously no! Unlike hardware, it is very difficult to "assemble" an application from software components. Since the advent of computer 60 years ago, we have written tons and tons of programs. However, for each new application, we have to re-invent the wheels and write the program from scratch. Why re-invent the wheels? Traditional Procedural-Oriented languagesCan we do this in traditional procedural-oriented programming language such as C, Fortran, Cobol, or Pascal? Traditional procedural-oriented languages (such as C and Pascal) suffer some notable drawbacks in creating reusable software components:
In brief, the traditional procedural-languages separate the data structures and algorithms of the software entities. In the early 1970s, the US Department of Defense (DoD) commissioned a task force to investigate why its IT budget always went out of control; but without much to show for. The findings are:
The task force proposed to make software behave like hardware OBJECT. Subsequently, DoD replaces over 450 computer languages, which were then used to build DoD systems, with an object-oriented language called Ada. Object-Oriented Programming LanguagesObject-oriented programming (OOP) languages are designed to overcome these problems.
As an example, suppose you wish to write a computer soccer games (which I consider as a complex application). It is quite difficult to model the game in procedural-oriented languages. But using OOP languages, you can easily model the program accordingly to the "real things" appear in the soccer games.
Most importantly, some of these classes (such as Benefits of OOPThe procedural-oriented languages focus on procedures, with function as the basic unit. You need to first figure out all the functions and then think about how to represent data. The object-oriented languages focus on components that the user perceives, with objects as the basic unit. You figure out all the objects by putting all the data and operations that describe the user's interaction with the data. Object-Oriented technology has many benefits:
OOP BasicsClasses & InstancesClass: A class is a definition of objects of the same kind. In other words, a class is a blueprint, template, or prototype that defines and describes the static attributes and dynamic behaviors common to all objects of the same kind. Instance: An instance is a realization of a particular item of a class. In other words, an instance is an instantiation of a
class. All the instances of a class have similar properties, as described in the class definition. For example, you can define a class called " The term "object" usually refers to instance. But it is often used quite loosely, which may refer to a class or an instance. A Class is a 3-Compartment Box encapsulating Data and FunctionsA class can be visualized as a three-compartment box, as illustrated:
In other words, a class encapsulates the static attributes (data) and dynamic behaviors (operations that operate on the data) in a box. Class Members: The data members and member functions are collectively called class members. The followings figure shows a few examples of classes: The following figure shows two instances of the class Unified Modeling Language (UML) Class and Instance Diagrams: The above class diagrams are drawn according to the UML
notations. A class is represented as a 3-compartment box, containing name, data members (variables), and member functions, respectively. classname is shown in bold and centralized. An instance (object) is also represented as a 3-compartment box, with instance name shown as Brief Summary
Class DefinitionIn C++, we use the keyword class Circle { private: double radius; string color; public: double getRadius(); double getArea(); } class SoccerPlayer { private: int number; string name; int x, y; public: void run(); void kickBall(); } Class Naming Convention: A classname shall be a noun or a noun phrase made up of several words. All the words shall be initial-capitalized (camel-case). Use a singular noun for classname. Choose a meaningful and self-descriptive classname. For examples, Creating Instances of a ClassTo create an instance of a class, you have to:
For examples, suppose that we have a class called Circle c1(1.2, "red"); Circle c2(3.4); Circle c3; Alternatively, you can invoke the constructor explicitly using the following syntax: Circle c1 = Circle(1.2, "red"); Circle c2 = Circle(3.4); Circle c3 = Circle(); Dot (.) OperatorTo reference a member of a object (data member or member function), you must:
For example, suppose that we have a class called For example, Circle c1(1.2, "blue"); Circle c2(3.4, "green"); cout << c1.getArea() << endl; cout << c2.getArea() << endl; c1.radius = 5.5; c2.radius = 6.6; Calling In general,
suppose there is a class called Data Members (Variables)A data member (variable) has a name (or identifier) and a type; and holds a value of that particular type (as descried in the earlier chapter). A data member can also be an instance of a certain class (to be discussed later). Data Member Naming Convention: A data member name shall be a noun or a noun phrase made up of several words. The first word is in lowercase and the rest of the words are initial-capitalized (camel-case), e.g., Member FunctionsA member function (as described in the earlier chapter):
Member Function Naming Convention: A function name shall be a verb, or a verb phrase made up of several words. The first word is in lowercase and the rest of the words are initial-capitalized (camel-case). For example, Take note that data
member name is a noun (denoting a static attribute), while function name is a verb (denoting an action). They have the same naming convention. Nevertheless, you can easily distinguish them from the context. Functions take arguments in parentheses (possibly zero argument with empty parentheses), but variables do not. In this writing, functions are denoted with a pair of parentheses, e.g., Putting them Together: An OOP ExampleA class called Three instances of In this example, we shall keep all the codes in a single source file called CircleAIO.cpp
To compile and run the program (with GNU GCC under Windows): > g++ -o CircleAIO.exe CircleAIO.cpp > CircleAIO Radius=1.2 Area=4.5239 Color=blue Radius=3.4 Area=36.3169 Color=red Radius=1 Area=3.1416 Color=red ConstructorsA constructor is a special function that has the function name same as the classname. In the above Circle(double r = 1.0, string c = "red") { radius = r; color = c; } A constructor is used to construct and initialize all the data members. To create a new instance of a class, you need to declare the name of the instance and invoke the constructor. For example, Circle c1(1.2, "blue"); Circle c2(3.4); Circle c3; A constructor function is different from an ordinary function in the following aspects:
Default Arguments for FunctionsIn C++, you can specify the default value for the trailing arguments of a function (including constructor) in the function header. For example,
"public" vs. "private" Access Control ModifiersAn access control modifier can be used to control the visibility of a data member or a member function within a class. We begin with the following two access control modifiers:
For example, in the above CircleAIO.cpp:8:11: error: 'double Circle::radius' is private Try moving On the other hand,
the function UML Notation: In UML notation, Information Hiding and EncapsulationA class encapsulates the static attributes and the dynamic behaviors into a "3-compartment box". Once a class is defined, you can seal up the "box" and put the "box" on the shelve for others to use and reuse. Anyone can pick up the "box" and use it in their application. This cannot be done in the traditional procedural-oriented language like C, as the static attributes (or variables) are scattered over the entire program and header files. You cannot "cut" out a portion of C program, plug into another program and expect the program to run without extensive changes. Data member of a class are typically hidden from
the outside word, with This follows the principle of information hiding. That is, objects communicate with each others using well-defined interfaces (public functions). Objects are not allowed to know the implementation details of others. The implementation details are hidden or encapsulated within the class. Information hiding facilitates reuse of the class. Rule of Thumb: Do not make any data member Getters and SettersTo allow other to read the value of a To allow other classes to modify the value of a For example, in our There
is no way you can change the If the designer of the void setColor(string c) { color = c; } void setRadius(double r) { radius = r; } With proper implementation of information hiding, the designer of a class has full control of what the user of the class can and cannot do. Keyword "this"You can use keyword " One of the main usage of keyword class Circle { private: double radius; ...... public: void setRadius(double radius) { this->radius = radius; } ...... } In the above codes, there are two identifiers called " Alternatively, you could use a prefix (such as class Circle { private: double m_radius; ...... public: void setRadius(double radius) { m_radius = radius; } ...... } C++ Compiler internally names their data members beginning with a leading underscore ( "const" Member FunctionsA double getRadius() const { radius = 0; // error: assignment of data-member 'Circle::radius' in read-only structure return radius; } Convention for Getters/Setters and ConstructorsThe constructor, getter and setter functions for a class Aaa { private: T xxx; public: Aaa(T x) { xxx = x; } Aaa(T xxx) { this->xxx = xxx; } Aaa(T xxx) : xxx(xxx) { } T getXxx() const { return xxx; } void setXxx(T x) { xxx = x; } void setXxx(T xxx) { this->xxx = xxx; } } For a private: bool xxx; public: bool isXxx() const { return xxx; } void setXxx(bool x) { xxx = x; } void setXxx(bool xxx) { this->xxx = xxx; } Default ConstructorA default constructor is a constructor with no parameters, or having default values for all the parameters. For example, the above Circle c1; Circle c1(); // Error! // (This declares c1 as a function that takes no parameter and returns a Circle instance) If C++, if you did not provide ANY constructor, the compiler automatically provides a default constructor that does nothing. That is, ClassName::ClassName() { } Compiler will not provide a default constructor if you define any constructor(s). If all the constructors you defined require arguments, invoking no-argument default constructor results in error. This is to allow class designer to make it impossible to create an uninitialized instance, by NOT providing an explicit default constructor. Constructor's Member Initializer ListInstead of initializing the private data members inside the body of the constructor, as follows: Circle(double r = 1.0, string c = "red") {
radius = r;
color = c;
} We can use an alternate syntax called member initializer list as follows: Circle(double r = 1.0, string c = "red") : radius(r), color(c) { } Member initializer list is placed after the constructor's header, separated by a colon ( It is recommended to use member initializer list to initialize all the data members, as it is often more efficient than doing assignment inside the constructor's body. *DestructorA destructor, similar to constructor, is a special function that has the same name as the classname, with a prefix If you do not define a destructor, the compiler provides a default, which does nothing. class MyClass { public: ~MyClass() { } ...... } Advanced Notes
*Copy ConstructorA copy constructor constructs a new object by copying an existing object of the same type. In other words, a copy constructor takes an argument, which is an object of the same class. If you do not define a copy constructor, the compiler provides a default which copies all the data members of the given object. For example, Circle c4(7.8, "blue");
cout << "Radius=" << c4.getRadius() << " Area=" << c4.getArea()
<< " Color=" << c4.getColor() << endl;
Circle c5(c4);
cout << "Radius=" << c5.getRadius() << " Area=" << c5.getArea()
<< " Color=" << c5.getColor() << endl;
The copy constructor is particularly important. When an object is passed into a function by value, the copy constructor will be used to make a clone copy of the argument. Advanced Notes
*Copy Assignment Operator (=)The compiler also provides a default assignment operator ( Circle c6(5.6, "orange"), c7; cout << "Radius=" << c6.getRadius() << " Area=" << c6.getArea() << " Color=" << c6.getColor() << endl; cout << "Radius=" << c7.getRadius() << " Area=" << c7.getArea() << " Color=" << c7.getColor() << endl; c7 = c6; cout << "Radius=" << c7.getRadius() << " Area=" << c7.getArea() << " Color=" << c7.getColor() << endl; Advanced Notes
Separating Header and ImplementationFor better software engineering, it is recommended that the class declaration and implementation be kept in 2 separate files: declaration is a header file " I shall illustrate with the following examples. Example: The Circle ClassInstead of putting all the codes in a single file. We shall "separate the interface and implementation" by placing the codes in 3 files.
Circle.h - Header
Program Notes:
Header files shall contains constants, function prototypes, class/struct declarations. Circle.cpp - Implementation
Program Notes:
Compiling the Circle ClassYou can compile the > g++ -c Circle.cpp To use the TestCircle.cpp - Test DriverLet's write a test program to use the
Compiling the Test ProgramTo compile > g++ -o TestCircle.exe TestCircle.cpp Circle.o You can also compile > g++ -o TestCircle.exe TestCircle.cpp Circle.cpp Example: The Time ClassLet's write a class called The class
Let's write the code for the Header - Time.h
Dissecting Time.h#ifndef TIME_H class Time { private: Only member function prototypes are listed in the class declaration. A function prototype consists of the return-type, function name and parameter types. Time(int h = 0, int m = 0, int s = 0); In the function prototypes of the header, we can set the default values of the function's parameters for any function member using " Time t1(1, 2, 3); Time t2(1, 2); Time t3(1); Time t4; The identifiers int getHour() const; void setTime(int h, int m, int s); void print() const; void nextSecond(); Implementation - Time.cpp
Dissecting Time.cppThe implementation file All member's identifiers in the implementation are preceded by the classname and the scope resolution operator ( Time::Time(int h, int m, int s) { The default values of the parameters are specified in the class declaration (in the header), NOT in the function definition. Placing a default value in function definition (e.g., Take note that we have not included input validation (e.g., hour shall be between 0 and 23) in the constructor (and setters). We shall do that in the later example. int Time::getHour() const { void Time::setHour(int h) { The rest of the function definitions are self-explanatory. "this" PointerInstead of naming the function parameters Time::Time(int hour, int minute, int second) { this->hour = hour; this->minute = minute; this->second = second; } Time::setHour(int hour) { this->hour = hour; } Time::getHour() const { return this->hour; } Member Initializer ListC++ provide an alternative syntax to initialize data members in the constructor called member initializer list. For example, Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {
} The
member initializer list is placed after the function parameter list, separated by a colon, in the form of The data members in the initializer list are initialized in the order of their declarations in the class declaration, not the order in the initializer list. Test Driver - TestTime.cpp
Dissecting TestTime.cppThe test driver tests the constructor (with and without the default values) and all the public member functions. Clearly, no input validation is carried out, as reflected in instance ExerciseAdd member functions Compiling the ProgramYou can compile all the source file together to get the executable file as follows: > g++ -o TestTime.exe Time.cpp TestTime.cpp
> TestTime Alternatively, you can compile > g++ -c Time.cpp
> g++ -o TestTime.exe TestTime.cpp Time.o
> TestTime Example: The Point ClassThe In the class diagram, " The
Point.h - Header
Point.cpp - Implementation
TestPoint.cpp - Test Driver
Example: The Account ClassA class called
Header file - Account.h
Implementation file - Account.cpp
Test Driver - TestAccount.cpp
Example: The Ball classA
Header File - Ball.h
Implementation File - Ball.cpp
Test Driver - TestBall.cpp
Let's start with the Author classLet's begin with a class called
Header File - Author.h
Implementation File - Author.cpp
Dissecting the Author.cppAuthor::Author(string name, string email, char gender) { if (gender == 'm' || gender == 'f') { void Author::setEmail(string email) { TestAuthor.cpp
A Book is written by an Author - Using an "Object" Data MemberLet's design a
The hallow diamond shape in the class diagram denotes aggregation (or has-a) association relationship. That is, a Header File - Book.h
#include "Author.h" private: Implementation File - Book.cpp
Book::Book(string name, Author author, double price, int qtyInStock) void
Book::setPrice(double price) { string Book::getAuthorName() const { TestBook.cpp
The Default Copy ConstructorThe initializer Author::Author(const Author& other) : name(other.name), email(other.email), gender(other.gender) { } Pass-by-Reference for Objects Function Parameters Author and stringBy default, objects are pass-by-value into functions. That is, a clone copy is created and pass into the function, instead of the original copy. Pass-by-value for huge objects depicts performance due to the overhead of creating a clone copy. Instead, we could pass an object into function by reference, via the reference ( In the Let's modify our Author.h
Program Notes:
Author.cpp
Program Notes:
Book.h
Program Notes:
Book.cpp
Test Driver - TestBook.cpp
In the above test program, an instance of SummaryAll the codes in this version of example (using references) is exactly the same as the previous version (without using references), except that the object function parameters are marked with " Link to "C++ References & Resources" How do you know if an object is an instance of a class?The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Which of the following is correct an object is an instance of its class?Explanation: An object is instance of its class. It can be declared in the same way that a variable is declared, only thing is you have to use class name as the data type.
What is an object an object is an instance of a class?an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave. method: a method is an action which an object is able to perform.
Which method can you use to determine whether an object is an instance of a class python?The Python's isinstance() function checks whether the object or variable is an instance of the specified class type or data type. For example, isinstance(name, str) checks if name is an instance of a class str .
|