For you new programmers or programmers new to OOP, this article will briefly explain the four principles that make object-oriented languages: encapsulation, data abstraction, polymorphism and inheritance. All the examples in VB.Net, because I think it's easier for new programmers to read and understand the PLO in the first place. Of course, I do not think I said you need a language. NET on the other, because they are all based on the CLR / CLS, and finally all together in one compilation of the language. His preference, which determines the language you use. Of course, there are other OOP languages out there, as Ruby, an object-oriented language that is pure and hybrid languages such as Python, C and Java, to name a few.
Encapsulation:
What is encapsulation? Well, in general, encapsulation to hide implementation data by restricting access to the access and switches. First, let's define the access and switches.
Accessor: Access is the method used to object to ask yourself. In OOP, they tend to be in the form of properties, which under normal circumstances, GET method, the method of access. However, access methods are not limited to properties and public method that gives information about the state of the object.
Public class person
"We use private property to perform here to hide
"Name, which is used for internal implementation of the individual.
Private _fullName As String = "Raymond Lewallen"
"It acts as an access. For the applicant, he hides
Realization of the full name and where he is and what
In determining its value. It gives only the state FullName
Person object, and nothing more. In another class, please call
"Person.FullName () returns" Raymond Lewallen ".
"There are other things we need to create an instance of
"Not first class, but that's another discussion.
FullName Property Public ReadOnly () As String
Get
Back _fullName
Get end
End Property
End Class
Mutator:
Setters are public methods that are used for object's status to change, while hiding implementation, as it is changing the data. Switches are often different parts of the building above, but this time the method of its game, which allows the caller to change according to participants in the wings
Public class person
"We use private property to perform here to hide
"Name, which is used for internal implementation of the individual.
Private _fullName As String = "Raymond Lewallen"
"This building is currently the getters and setters. We still have
Covert FullName.
Public Property FullName () As String
Get
FullName Back
Get end
Set (ByVal value as String)
Value _fullName =
Set end
End Property
End Class
Well, now you can look at another example, access, and the switch includes:
Public class person
Private _fullName As String = "Raymond Lewallen"
"This is another example of the access method
"If this time we use the function.
Public GetFullName () As String
Back _fullName
End Function
"This is an example of one mutator method
"If this time we use a subroutine.
Public Sub setFullName (ByVal NewName As String)
_fullName = NewName
End Sub
End Class
Thus, the use of access and switches have many advantages. Hiding the implementation of our class Person, we can make changes to class rights without fear that we are violating the code that uses the other, and encouraging class person for the information. If we wanted, we could see the full name of the string to change to an array of unique characters (FYI, this is what the string object is actually behind the scenes), but the call never know, because we will always return a string FullName, but behind scenes that we are dealing with an array of characters instead of a string object. Transparent to the rest of the program. This type of data protection and the implementation is called encapsulation. Think about access and manipulators, some of the information surrounding the form class.
Abstract:
Data abstraction is the simplest principles of understanding. Data extraction and encapuslation closely linked, since a simple definition of data abstraction is the development of classes, objects, data types, in accordance with their interfaces and functionality, not implementation details. Abstraction refers to the model, view, or another representative nominated for the real object. His development of the software object to represent an object, we find in the real world. Encapsulation hides the implementation details.
Abstraction is used to manage complexity. Developers use abstraction to decompose complex systems into smaller components. Progress and development, programmers familiar with the functions that they can expect from unused subsystems. Thus, programmers are not charged waysin taking into account that the implementation of subsystesm later, the drafting of earlier influences.
The best definition of abstraction that I have ever read this: "abstraction provides the essential features of an object that distinguish it from all other kinds of objects and thus provide a clearly defined conceptual boundaries, relative to the eye of the beholder." - G. Booch, Object-oriented design with applications, Benjamin / Cummings, Menlo Park, Calif., 1991.
Public class person
Private _height As Int16
The depth of the Public Domain () As Int16
Get
Return _height
Get end
Set (ByVal Value Int16)
_height = Value
Set end
End Property
_weight As Int16 Private
Weight of the public domain () As Int16
Get
Back _weight
Get end
Set (ByVal Value Int16)
Value _weight =
Set end
End Property
_age As Int16 Private
Age of public ownership () As Int16
Get
Back _age
Get end
Set (ByVal Value Int16)
Value _age =
Set end
End Property
Public Sub Sit ()
Code, that person is sitting
End Sub
Public Sub Run ()
Code, that person's authority
End Sub
Public Sub Cry ()
Code that someone cries
End Sub
Public CanRead () As Boolean
The code that determines whether a person who can read
And give true or false
End Function
End Class
Inheritance:
Now let's talk about heritage. Objects can relate to each other or with the "A", "use" or "relationship. "Is" is the way of heritage object relations. An example of what has always stuck with me over the years is the library (I think I could read something written by Grady Booch). So take the library, for example. More than one library makes books, but also magazines, audio and microfilm. At some level, all these elements are treated equally: four types of assets represent a library that can be equivalent to men. However, even if the four species can be considered as well, they are not identical. The book ISBN and charger is not. And audio tapes duration of the game and microfilm can be checked during the night.
Each of these library resources should be provided its own definition of the class. Without inheritance, each class independently perform functions common to all credit assets. All assets, either check or available for order. All assets have a name, date of purchase and replacement cost. Instead of duplicating functions inherited inheriting functionality from another class, called the base class or superclass.
Let's look at the major asset classes of credit. It will be used as a basis for asset classes such as books and audio cassettes.
Public Asset Class Library
_title As String Private
State property () As String
Get
Back _title
Get end
Set (ByVal value as String)
Value _title =
Set end
End Property
_checkedOut As Boolean Private
CheckedOut Public Domain () As Boolean
Get
Back _checkedOut
Get end
Set (ByVal value as Boolean)
Value _checkedOut =
Set end
End Property
How _dateOfAcquisition private DateTime
DateOfAcquisition Public Domain () As DateTime
Get
Back _dateOfAcquisition
Get end
Set (ByVal value as DateTime)
Value _dateOfAcquisition =
Set end
End Property
_replacementCost As Double Private
replacement cost in the public domain () as double
Get
Back _replacementCost
Get end
Set (ByVal value as Double)
Value _replacementCost =
Set end
End Property
The end of the library asset classes is a superclass or base class that contains data and methods common to all assets of the post supports. Books, magazines, audio and microfilm all subclasses or derived classes or library of asset classes and they inherit these characteristics. Inheritance relationship is called a "relationship. Book of the Library's assets, as well as three other assets.
Let the classes of books and audio cassettes, which are inherited from the asset class library:
Public class Book
Inherited assets library
_author As String Private
The author is in the public domain () As String
Get
Back _author
Get end
Set (ByVal value as String)
Value _author =
Set end
End Property
_isbn As String Private
Isbn Public Domain () As String
Get
Back _isbn
Get end
Set (ByVal value as String)
Value _isbn =
Set end
End Property
End Class
Public class Audio Cassettes
Inherited assets library
_playLength As Int16 Private
Play the length of the Public Domain () As Int16
Get
Back _playLength
Get end
Set (ByVal Value Int16)
Value _playLength =
Set end
End Property
End Class
Now, let's take an instance of the book, so we have a new book in the library list for registration:
Sun MyBook Book = New Book
myBook.Author = "Sahil Malik"
myBook.CheckedOut = False
myBook.DateOfAcquisition = # 15/02/2005 #
myBook.Isbn = "0-316-63945-8"
myBook.ReplacementCost = 59,99
myBook.Title = 'Best book you ever buy Ado.Net "
You see, when we have a new book, we have all the features an asset class library at our disposal, but also because we have inherited from the class. Methods can be inherited. Let's add some methods to our asset class library:
Public Asset Class Library
"Imagine that the above properties
Public Sub exit ()
If not, then _checkedOut _checkedOut = True
End Sub
Public Sub Estimate ()
Then, if _checkedOut _checkedOut = False
End Sub
End Class
Polymorphism
Polymorphism means one name many forms. Polymorphism manifests itself in multiple methods with the same name but with slightly different functionality. VB6ers Many customers are familiar with the interface polymorphism. I'm not going to discuss the polymorphism in terms of inheritance, and the part that is new to many people. For this reason it may be difficult to fully understand the potential for polymorphisms to yield in practice and what is happening in different situations to see. We will only talk about polymorphism, as well as other actors at the beginning of the study.
There are two types of polymorphism. Overridden, also known as run-time polymorphism, and overloading, which is called the compilation of polymorphism. This difference, method overloading, the compiler determines which method will be executed, and that decision is made when the code is compiled. Which method will be used to override the method determined at runtime based on dynamic type of object.
Public class MustInherit asset library
Penalty for lack of a single day for overdue items
Private _finePerDay Const As Double = 1.25
"Term for an item that has been tested
How _dueDate private DateTime
Public Property DueDate () As DateTime
Get
Back _dueDate
Get end
Set (ByVal value as DateTime)
Value _dueDate =
Set end
End Property
"Calculate the amount of the fine standard for the delay element
CalculateFineTotal Overridable Public Function () as double
As Int32 = daysOverdue CalculateDaysOverdue (Sun)
If daysOverdue> 0 Then
Go _finePerDay daysOverdue
Other
0.0 Back
End If
End Function
'Calculate the number of days late for a return
CalculateDaysOverdue protective function () As Int32
(DateTime.Now DateInterval.Day, _dueDate, ()) DateDiff Back
End Function
End Class
"The class that inherits from the library assets Magazine
NotInheritable Public Class Magazine
Inherited assets library
End Class
The book is a class inherits an asset library
NotInheritable Public Class Book
Inherited assets library
"It's morphing CalculateFineTotal () function of the base class.
"This feature replaces the base class, and any appeal
From any class copy of the book CalculateFineTotal
"With this feature, not a base class function.
"This type of polymorphism is called dominant.
CalculateFineTotal Overrides Public Function () as double
As Int32 = daysOverdue CalculateDaysOverdue (Sun)
If daysOverdue> 0 Then
Go daysOverdue 0,75
Other
0.0 Back
End If
End Function
End Class
Components involved in the PLO
Components: objects, classes (public, private), methods (public, private), variables (public, private), collectors' items are essential for the understanding of object-oriented technology. Look around and you'll find many examples of real-world objects: your dog, desk, TV, bicycle.
real objects have two characteristics: they all have state and behavior. Dogs are able to (name, color, breed, hungry) and behavior (barking, recovery, wagging his tail). Cycling is also (current speed, current pedal cadence, current speed) and behavior (gear, changing pedal cadence, applying brakes). State and behavior of objects in the real world is a great way to start thinking in terms of object-oriented programming.
Take a minute right to real-world objects in the vicinity to watch. For each element, you see, you ask two questions: "What could the possible states for this purpose" and make sure to write your comments: "What possible problem could object." . If you do, you'll notice that the real-world objects vary in complexity, your desk, only two possible states (on and off) and two possible behaviors (Turn, Turn), but your office may have different states of the radio (in, out, current volume, the current drive) and behavior (turn, turn, increase volume, decrease volume, scan and melody). You may also notice that some objects that turn other objects. These observations of real world translates into the world of object-oriented programming.
Bicycle modeled as a software object.
Assigning state (current speed, current pedal cadence, current and speed) and providing methods for changing this state of the object remains in control as the outside world are allowed. For example, if the bike is only 6-speed, method of changing the speed value is lower than 1 or greater than 6 reject.
Grouping the individual code of the software has several advantages, including:
1. Modularity: the source code of the object can be recorded and maintained regardless of the source code for other objects. Once created, the object can be easily moved throughout the system.
2. Information-hiding: By interacting only with the methods of the object, to keep the details of its internal implementation is hidden from the outside world.
3. reuse of code: If the object already exists (perhaps written by another software developer), you can object in your program. This allows technicians to perform / / debugging of complex objects that are specific to the tasks, then you trust your own code to run the tests.
4. Easy installation and debugging: if an object is a particular problem, you can request and simply remove the plug to another object as a replacement. This is analogous to solving mechanical problems in the real world. In the event of failure of the bolts to be replaced, but not the whole machine.
What is the class:
In the real world, you often find many individual objects of the same nature. There may be thousands of other bicycles in existence, all the same make and model. Each bike was built from the same set of plans and, therefore, contains the same ingredients. In connection with the object-oriented, we say that your bicycle is an instance of a class of objects known as cycling. Class template from which individual objects are created.
The next category of bikes is the possibility of bike:
class Bicycle {
Int cadence = 0;
Int speed = 0;
Int gear = 1;
changeCadence void (INT NewValue) {
cadence = NewValue;
}
Gear void change (INT NewValue) {
Speed = NewValue;
}
Void SpeedUp (INT gain) {
Speed = speed increase;
}
Apply the brakes as invalid (INT below) {
speed = speed - decrease;
}
Station void print () {
System.out.println ("cadence:" speed "speed" speed "gear");
}
}
The syntax of the Java programming language a new look at you, but the design of this class based on the earlier discussion of bicycle facilities. Rate of pitch, speed and acceleration of the object state and methods (changeCadence, switching speeds, etc.) as a means to determine their interaction with the outside world.
Class bicycle {demo
public static void main (String [] args) {
/ / Create two different objects Bike
Bike1 bike new bike = ();
Bike2 Bike = New ();
/ / Call methods on these objects
bike1.changeCadence (50);
bike1.speedUp (10);
bike1.changeGear (2);
bike1.printStates ();
bike2.changeCadence (50);
bike2.speedUp (10);
bike2.changeGear (2);
bike2.changeCadence (40);
bike2.speedUp (10);
bike2.changeGear (3);
bike2.printStates ();
}
}
Exit this test prints the end of cadence, speed and equipment for the bike:
Speed: 50 Speed: 10 gears: 2
speed: 40 Speed: 20 Speed: 3
Variables
As you learned in the previous chapter, the object stores the state of the fields.
Int cadence = 0;
Int speed = 0;
Int gear = 1;
What is the purpose? discussion of field settings, but you probably have some questions: What are the rules and conventions for the naming of the field? Int Furthermore, what types of data than others? Add a field must be initialized when they report? fields get a default value if not explicitly initialized? We will explore answers to these questions in this lesson, but before we can, there are some technical differences you must know. In Java, the terms "domain" and "variable" are used equally, which is often a source of confusion for new developers, because the two often seems to refer to the same thing.
The Java programming language defines the types of variables:
• instance variables (non-static field) Technically speaking, the storage of individual objects, non-static fields of their states, that is, fields declared without the static keyword. Non-static fields, also known as instance variables because their values are specific to each instance of the class (each object, in other words), the current speed bike current speed independent of each other.
• Variable class (static fields) of the class variable region indicates the static modifier, the compiler that there is exactly one copy of this variable in existence told, no matter how many times the class was created. Field with the number of transmissions for a certain type of bike will be marked as stable with conceptually the same number of gears will be applied to all cases. NumGears static Int code = 6; create a static field. In addition, the final keyword can be added to indicate that the amount of equipment will never change.
• Local residents, just as object stores its state in fields, often using to store the temporary state in local variables. The syntax for declaring a local variable which is equal to the field (eg Int Count = 0). There is no special keyword destination variable, as local decision comes entirely from the place where the variable is declared - that lies between the opening and closing parentheses of the method. Thus, local variables are only available for methods that were declared, they are not accessible from the rest of the class.
• The settings you've already seen examples of parameters, both in the classroom, and a bicycle in the main method of "Hello World" application. Remember that the main method signature public static void main (String [] args). Here, the variable arguments to this method. It is important to remember that the parameters are always classified as "variable" rather than "field". This option applies to other buildings and to take (for example, builders and managers of exceptions), you will learn at the end of the textbook.
Nevertheless, the rest of this tutorial uses the following rules when considering the fields and variables. When we speak of "fields in general (except for local variables and parameters), we can simply say:" field, all the above, we can simply say: "variable" "In discussing the concerns.." If the context, the distinction, we use specific terms (static fields, local variables, etc.), if any. Sometimes you can see the term "member" are used together. Form fields, methods and nested types are collectively called its members.
Title
Each programming language has its own set of rules and conventions in the form of names that you have the right to use, and the Java programming language is no exception. Rules and conventions for naming variables can be summarized as follows:
• Variable names are case-sensitive. The variable name can be any legal identifier - a sequence of unlimited length Unicode letters and digits, beginning with the letter, a dollar sign "$" or the "_". The agreement is always your variable names start with the letter, rather than "$" or "_". In addition, the dollar sign, by convention, never used at all. Find a situation where the names of the independent organization, the dollar sign, but the variable names should avoid using them. A similar agreement exists for the underscore, and is technically legal to begin with the name of your variable with "_", this practice is discouraged. Spaces are not allowed.
• The following characters can be letters, numbers, dollar signs, or underscore. Conventions (and common sense) apply to this rule. When you call your variables to choose to use whole words rather than cryptic abbreviations. This will make your code easier to read and understand. In many cases it will also make your own code to the document, called the cadence of the field, velocity and acceleration, for example, is much more intuitive than abbreviated versions, such as S, C and G. Keep in mind that the name you choose, there should be a keyword or keyword.
• If the name you choose is made of a single word, written word in lowercase. If it consists of a few words below the first letter of each word. Names and gearratio current transmission are excellent examples of this Convention. If your variable stores a constant value, as NUM_GEARS static final Int = 6, the Convention of the changes, capitalize every letter and separate words with underscores. By convention, the underscore is not used elsewhere.
Determination methods
Here's an example declaration of the traditional method:
public double calculateAnswer (wingspan double Int numberOfEngines, double length, double gross registered tons) {
/ / Do calculation here
}
Only the necessary elements of the method declaration of a method that returns a name, a pair of brackets (), and body in braces {}.
In general, the method returns six parts, in order:
1. Modifiers, such as public, private, and others, you will learn later.
2. Return type of the data type of the return value of method, or null if the method returns no value.
3. The name of the method of "rules of the domain refers to the method names as well, but the Convention is a little different.
4. Parameter list in parentheses, a comma separated list of input parameters, preceded by their data types, separated by parentheses (). If there are no parameters, you need parentheses.
5. The list of exceptions that will be discussed later.
6. The method body lift method code, including the declaration of local variables goes here.
Naming Method
Even if the method name can be any legal identifier code conventions to limit the method names. By convention, method names must be lowercase verb or multi-word name that starts with a lowercase verb, then adjectives, nouns, etc. In the name of several words, the first letter of each half and after the word must be capitalized. Here are some examples:
Run
RUNFASTER
getBackground
getFinalData
CompareTo
set X
IsEmpty
Typically, the method has a unique name in its category. However, this method have the same name as the other methods because the method of overload.
Overloading Methods
The Java programming language supports method overloading, and Java can distinguish between methods with different method signature. This means that the methods in the class may have the same name, as they have a list of options (there are some caveats to be discussed in class, entitled "Interfaces and Inheritance").
Suppose you have a class that you can use calligraphy to attract different types of data (strings, numbers, etc.) and a method for each type of data to pull. Difficult new name for each method, for example, draw string, integer, draw, draw, swim, and so on. In the programming language Java, you can use the same name for all drawing techniques, but there is another list of arguments for each method. Thus, the data for drawing class to explain the four methods named draw, each with a different parameter list.
Data {People's Artist of the class
...
public void draw (String S) {
...
}
public void draw (Int I) {
...
}
public void draw (double F) {
...
}
public void draw (INT I double F) {
...
}
}
Overloaded methods differ in the number and nature of the arguments that are passed into the method. The code sample, draw (String) and set (Int I) are separate and unique ways as they require different kinds of arguments.
You can not explain more than one method with the same name and number and type of arguments because the compiler can not distinguish