Private nested classes - are they necessary for composition? - class

This is my naive thought process. I appreciate when anyone points out any discrepancies.
I know that in Java it is possible to create private nested classes. But in PHP (calling itself an "OOL") no such thing is easily possible.
However, there may be an instance where I need to use a helper class within only one other class.
This naturally led me to consider using composition about which I think its supposed to actually solve this kind of a problem, for the following reason:
Wikipedia:
It is only called composite, if the objects it refers to
are really its parts, i.e. have no independent existence.
Aggregation differs from ordinary composition in that it does not imply ownership.
In composition, when the owning object is destroyed, so are the
contained objects. In aggregation, this is not necessarily true.
So since in composition the components aren't supposed to exist without the other composite object, I assume there is basically only one way of accomplishing this by using private nested classes, otherwise I will need to have the Component class visible, making it instantiable also somewhere else, violating the creation/destruction-of-components-within-the-composite-class rule.
Now I came across PHP where it is not possible at all to create nested classes (or maybe with some magic) which may lead to a question why do we need nested classes at all?
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one
place: If a class is useful to only one other class, then it is
logical to embed it in that class and keep the two together. Nesting
such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B,
where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared
private and B can access them. In addition, B itself can be hidden
from the outside world.
It can lead to more readable and maintainable code: Nesting small
classes within top-level classes places the code closer to where it is
used.
So in my opinion, as nested classes increase encapsulation (and thus allowing for implementation of a composite concept) it should be always possible to create a nested class in a proper OOL.
I also looked up the definition of an OOP and it only mentions the support for Encapsulation, Abstraction, Inheritance, Polymorphism concepts.
OOP
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s
definition.
Abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. (e.g. instead or creating a single sequence of commands to work with a radius and points we would abstract a concept of a circle. So we define a class Circle and a its attributes/functions in such a way that it reflects this abstract concept.)
Inheritance is supposed to be the is-a relationship between abstractions (allowing for code reuse).
Polymorphism allows for overriding and overloading methods.
A guy asked a question here which actually complies exactly with my understanding of the problem and IMHO received quite inaccurate answer, being told to be really confused and being provided with a code sample which IMO is not a proper composition, as it is not really possible in PHP. In addition someone may argue that composition isn't about inner classes.
So am I understanding something really wrong?

Those concepts like composition are generic and their implementation may vary depending on the programming language.
In the other hand, I wouldn't say that the definition of composition which includes [...] have no independent existence refers to being able to create instances or not from different scopes.
No independent existence is a more conceptual than practical rule. It means that a wheel can never be the composition root because the root is the car. That is, a wheel can't exist independently of a car.
Therefore, the conclusion is nested classes are just an implementation detail and they have nothing to do with composition. Note that objects aren't created from classes in all programming languages but composition and many other features are still possible. Would you say that object composition isn't possible in JavaScript?
var car = { manufacturer: "Ford", model: "Focus" };
// I can create the wheel after the car
var wheel = { color: "black" };
// but it'll be always tied to some car
car.wheel = wheel;
Anyway, practically all systems implement aggregation, which is a flavor of composition. Take a look at this Q&A at Software Engineering.
While a wheel is useless without being part of a car, wheels are still sold apart as one of the many mechanical pieces of which a car is built, hence a wheel can live alone yet it's useless as just a piece.
Generic definition of composition in OOP
The OP is too concerned and focused on the formal definition of composition in terms of UML: composition, association, direct association, aggregation...
BTW, the term composition in OOP has a more simple meaning which is often used, for example, when discussing when to use inheritance or when to avoid it, we talk about composition over inheritance. See for example this Q&A from 2010: What is composition as it relates to object oriented design? on which basically all answerers have a consensus about the definition of composition.
At the end of the day, the term composition is the approach to create an object graph: simple types are associated together to create more complex types.
Thus, as I've already explained in the first part of this answer, nested classes are just a programming language implementation detail and they're not crucial to implement any flavor of composition.
OP said on some comment:
But conceptually in order to implement it properly as a composition,
I'd prefer something like partial classes (as in C#) allowing me to
separate code into multiple files but restricting the instantiability
to the main class only. I know you don't agree with me, I have to
express my view somehow.
This is a wrong example because partial classes are just a syntactic sugar to glue multiple files defining the same class and later everything is the same class.
C# has nested classes:
public class A
{
public class B
{
}
}
But you need to understand that type definitions have nothing to do with objects from a conceptual point of view because an object-oriented language may or may not have a type system and classes, but yet it can support composition and all its flavors.

In wikipedia, there's also the following example of composition without using private nested classes.
class University
{
std::vector<Department> faculty; //this is composition
std::vector<People*> people; //this is aggregation
University() // constructor
{
// Composition: Departments exist as long as the University exists
faculty.push_back(Department("chemistry"));
faculty.push_back(Department("physics"));
faculty.push_back(Department("arts"));
}
};
For a true composition we don't have to make the whole class private as long as we treat instances of departments appropriately, i.e. we need to make sure that all departments will actually get deleted when the university ceases to exist.
An analogous ways of implementing different compositions in JavaScript would be as follows:
/*this is a component's "class"*/
function Text(txt){
this.txt = txt;
}
/*this is a composite's "class"*/
function Hello(begining){
/*public object*/
this.begining = begining;
/*this is like making an instance from a nested function which is a composite*/
var Middle = new (function Middle(txt){
this.txt = txt;
})(" - ");
/*private object - also a composite, even though it's made of the public class Text*/
var Ending = new Text("that's all.");
/*The use of the private property Ending*/
this.Say = function(){
var msg = this.begining.txt + Middle.txt + Ending.txt;
console.log(msg);
}
}
/*
This txt variable will be the "begining" text. It could still be a composite, but
only if it's not used in another composite when purpose is to be
"an untransferable part" and not a "visitor".
*/
var txt = new Text("Dan");
var say1 = new Hello(txt);
var say2 = new Hello(new Text("To be or not to be"));
say1.Say() /*Dan - that's all.*/
say2.Say() /*To be or not to be - that's all.*/
But even the transferability is often a neglected rule when people see "cars" having "wheels" as parts (rather then "visitors")
Instead of perhaps "neural network" and "neurons" or "forest" and "trees". Trees don't get replanted to a different forest so often.
And since the wheels can still be understood as parts of a composite, it doesn't have to differ from aggregation in code.

Related

Is it better to implement two classes or one class in the following case?

I have a class "Vertex" with 4 attributes and a class "Vertex_" with one attribute. The one attribute in Vertex_ is also in Vertex. Is it a good design to keep the two classes or is it better to program just the class Vertex, although there will be 3 variables, which are not used, when I instantiate an object which needs just the one attribute?
Class Vertex_ is actually somewhat a duplicate of Class Vertex.
I would suggest using inheritance and having Class Vertex inherit the attribute from the parent Class Vertex_ while having the 3 other attributes Class Vertex_ does not have.
TL;DR
This is a question that deserves a very long answer.There are two reasons for inheritance and the reason for doing it can depend on the language being used. One reason is for code reuse. Without knowing anything else about your situation, it would seem you are inheriting simply to reuse an attribute (but I suspect there could be more you will be reusing). But, there are other ways of getting code reuse without inheritance, for example containment, which is often a better way.
A powerful feature of object-oriented programming is the ability to substitute one type of object for another. When a message is sent to that object, the correct method implementation is invoked according the actual type of object receiving the message. This is one type of polymorphism. But in some languages the ability to substitute one object for another is constrained. In Java I can only substitute an instance of class B for an instance of class A if B is a descendant of A. So inheritance becomes important in Java to support polymorphism.
But what does it mean to be able to substitute a B instance for an A instance? Will it work? Class A has established a contract stating what each of its methods requires before you can successfully call it and at the same time states what each method promises to deliver. Will the methods of class B live up to that contract? If not, you really cannot substitute a B for an A and expect the program to run correctly. B may be a subclass of A but it is not a subtype of A (see Liskov substitution principle]).
In a language such as Python, inheritance is not required for polymorphism and coders are more apt to use it as code-reuse mechanism. Nevertheless, some people feel that subclassing should only be used to express subtyping. So, if Vertex_ is only using one of the four attributes it has inherited, I am doubtful that an instance of Vertex_ could be safely substituted for an instance of Vertex. I would not do the inheritance unless the language were C++ and then I would use private inheritance.

Why use accessors and mutators with simple classes?

For simple classes (and I mean really simple ones), why do we use accessor and mutator methods? Why do not we just make the data members public?
For example, the following class header (in C++) and could have been implemented with much less effort; as it is actually a couple of data members with accessors and mutators that do nothing but access/modify those data members.
I appreciate the advantage of the use of accessors and mutators in more complex classes.
template<class T>
class Node
{
private:
T item; // A data item
Node<T>* next; // Pointer to next node
public:
Node();
Node(const T& anItem);
Node(const T& anItem, Node<T>* nextNodePtr);
void setItem(const T& anItem);
void setNext(Node<T>* nextNodePtr);
T getItem() const;
Node<T>* getNext() const;
}; // end Node
This is a very fundamental, basic, and well-defined design principle in OOP - why to use accessors and mutators, in spite of whether a class is big or small.
I would still say, that implementation-usage of this principle still varies from language to language, but the core principle of Object Oriented Design - Encapsulation - remains always same and mandates, that you should always hide everything that is possible to hidden.
This is kind of duplicate of your question, and it refers to why getters and setters are in the play; however, I'll try to bring some other points as well.
Encapsulation, aspect of which is the topic in questions (mutators/accessors), is a fundamental and probably the most important principle of Object Oriented Programming.
First and foremost:
The main point of the Encapsulation is not(!) to restrict/block the access to the member variable, but rather to constrain the access policy and mandate the reasonable access, and therefore avoid any unintended interference, implicit misuse, or accidental accesses.
Think about it: if the user invokes .setUserName("MyUser") the one really intends to write the data into the member field, and that's explicitly clear! otherwise, it would mean that the client has (1) accidentally provided the "MyUser" data as an argument into setter method, and they (2) accidentally invoked the .setUserName method, which is way less likely to happen accidentally both together, then just publicly accessing that field, which takes only one move to do.
That being said, using the principle of encapsulation and advocating it as a core OOP feature, software developers, a lot of frameworks and libraries very often conventionally agree and make use of data classes, ordinary classes, business classes, service, or any other types, relying on the widespread Conventional Design and best practice of how to use member variables - using mutators to mutate and accessors to access the fields.
Many frameworks explicitly invoke setters and getters when they implement IoC or DI.
So, it's the best practice, conventionally agreed, non-smelling code style, and the most safe design of the class members, to use encapsulation and interact with them through mutators and accessors.

OOP relationships between two classes

I have been struggling with the abstraction that lies between two classes when it comes to the issue of Inheritance or Composition...the IS-A vs HAS-A relationship between classes like LoginManager and AuthenticateManager.
The way I see it LoginManager can be either and can sit comfortably in a IS-A place with AuthenticateManager, inheriting it as a superclass (ie Class LoginManager extends AuthenticateManager) OR just declare AuthenticateManager's objects as members of its own class which would imply Composition, so i guess it just comes down to a thing of experience and the proper knowledge of the OOP paradigm. So please, can anyone help explain what a proper relationship would be between these classes?
PS: Please moderator don't close this topic as being inconsistent with the sites question asking principles.
Thanks.
It depends on your needs. Inheritance provides you with access to protected members of a superclass whereas composition does not. If there are class members that should be available only to a derived class then it does not make sense to make them properties and access them with composition because every other object could access them as well. Otherwise it is about what you and your team prefer.
EDIT:
No rules are so strict as you think they are. Design patterns, for instance, are just templates and you don't need to strictly follow them. You can't blindly follow rules, no one will credit you for this. It's much better to have OOP in mind but write your code so that you can clearly explain what have you done and why.
Since I don't know design of your two classes, I can't really tell you what are your needs. This statement (already mentioned) should be enough to point you in the right direction.
Inheritance provides you with access to protected members of a superclass whereas composition does not.
Why not consider something that is easier to grasp?
I have a father - I inherit his genes (some good some bad?) But hey.
He had a kidney. His own and that made his composition.
I have my own kidney - my own and that makes my composition.
So
IS-A - I IS-A child of my father
HAve-A - I hAVE-A kidney
My Kidney works differently to my fathers
But I have blue eyes that I have inherited from my father

Why doesn't Scala have static members inside a class?

I know you can define them indirectly achieve something similar with companion objects but I am wondering why as a language design were statics dropped out of class definitions.
The O in OO stands for "Object", not class. Being object-oriented is all about the objects, or the instances (if you prefer)
Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism. Simply put, statics aren't object-oriented.
Scala, on the other hand, is object oriented. Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.
They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.
Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated. These things have no place in any well-designed language that wishes to describe itself as object-oriented.
Concerning why it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:
The way I look at it, though, is that singleton objects allow you to
do the static things where they are needed in a very concise way, but
also benefit from inheritance when you need to. One example is it is
easier to test the static parts of your program, because you can make
traits that model those parts and use the traits everywhere. Then in
the production program use a singleton object implementations of those
traits, but in tests use mock instances.
Couldn't have put it better myself!
So if you want to create just one of something, then both statics and singletons can do the job. But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.
In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.
I also posted this question on scala users google group and Bill Venners one of the authors of "Programming in scala" reply had some insights.
Take a look at this: https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/6vZJgi42TIMJ and https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/oTrLFtwGjpEJ
Here is an excerpt:
I think one
goal was simply to be simpler, by having every value be an object,
every operation a method call. Java's statics and primitives are
special cases, which makes the language more "complicated" in some
sense.
But another big one I think is to have something you can map Java's
statics to in Scala (because Scala needed some construct that mapped
to Java's statics for interop), but that benefits from OO
inheritance/polymorphism. Singleton objects are real objects. They can
extend a superclass or mix in traits and be passed around as such, yet
they are also "static" in nature. That turns out to be very handy in
practice.
Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) http://www.artima.com/scalazine/articles/goals_of_scala.html
Here is an excerpt:
First, we wanted to be a pure object-oriented language, where every value is an object, every operation is a method call, and every variable is a member of some object. So we didn't want statics, but we needed something to replace them, so we created the construct of singleton objects. But even singleton objects are still global structures. So the challenge was to use them as little as possible, because when you have a global structure you can't change it anymore. You can't instantiate it. It's very hard to test. It's very hard to modify it in any way.
To Summarize:
From a functional programming perspective static members are generally considered bad (see this post by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.
Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop).
These are the things that pop into my head when I think about how statics could complicate things:
1) Inheritance as well as polymorphism would require special rules. Here is an example:
// This is Java
public class A {
public static int f() {
return 10;
}
}
public class B extends A {
public static int f() {
return 5;
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.f());
B b = new B();
System.out.println(b.f());
A ba = new B();
System.out.println(ba.f());
}
}
If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like #Override annotation, which is of course optional and the friendly "The static method f() from the type A should be accessed in a static way" warning. This leads us to
2) The "static way" of accessing stuff is a further special rule, which complicates things.
3) Static members cannot be abstract. I guess you can't have everything, right?
And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.
It's true, static member don't exists, BUT, it's possible to associate a singleton object to each class:
class MyClass {
}
object MyClass {
}
to obtain similar results
Object oriented programming is all about objects and its states(Not touching state full and stateless objects in Java). I’m trying to stress “Static does not belong to objects”. Static fields cannot be used to represent a state of an object so it’s rational to pull off from objects.

How do I use classes?

I'm fairly new to programming, and there's one thing I'm confused by. What is a class, and how do I use one? I understand a little bit, but I can't seem to find a full answer.
By the way, if this is language-specific, then I'm programming in PHP.
Edit: There's something else I forgot to say. Specifically, I meant to ask how defining functions are used in classes. I've seen examples of PHP code where functions are defined inside classes, but I can't really understand why.
To be as succinct as possible: a class describes a collection of data that can perform actions on itself.
For example, you might have a class that represents an image. An object of this class would contain all of the data necessary to describe the image, and then would also contain methods like rotate, resize, crop, etc. It would also have methods that you could use to ask the object about its own properties, like getColorPalette, or getWidth. This as opposed to being able to directly access the color pallette or width in a raw (non-object) data collection - by having data access go through class methods, the object can enforce constraints that maintain consistency (e.g. you shouldn't be able to change the width variable without actually changing the image data to be that width).
This is how object-oriented programming differs from procedural programming. In procedural programming, you have data and you have functions. The functions act on data, but there's no "ownership" of the data, and no fundamental connection between the data and the functions which make use of it.
In object-oriented programming, you have objects which are data in combination with actions. Each type of data has a defined set of actions that it can perform on itself, and a defined set of properties that it allows functions and other objects to read and write in a defined, constraint-respecting manner.
The point is to decouple parts of the program from each other. With an Image class, you can be assured that all of the code that manipulates the image data is within the Image class's methods. You can be sure that no other code is going to be mucking about with the internals of your images in unexpected ways. On the other hand, code outside your image class can know that there is a defined way to manipulate images (resize, crop, rotate methods, etc), and not have to worry about exactly how the image data is stored, or how the image functions are implemented.
Edit: And one more thing that is sometimes hard to grasp is the relationship between the terms "class" and "object". A "class" is a description of how to create a particular type of "object". An Image class would describe what variables are necessary to store image data, and give the implementation code for all of the Image methods. An Image object, called an "instance" of an image class, is a particular use of that description to store some actual data. For example, if you have five images to represent, you would have five different image "objects", all of the same Image "class".
Classes is a term used in the object oriented programming (OOP) paradigm. They provide abstraction, modularity and much more to your code. OOP is not language specific, other examples of languages supporting it are C++ and Java.
I suggest youtube to get an understanding of the basics. For instance this video and other related lectures.
Since you are using PHP I'll use it in my code examples but most everything should apply.
OOP treats everything as an object, which is a collection of methods (functions) and variables. In most languages objects are represented in code as classes.
Take the following code:
class person
{
$gender = null;
$weight = null;
$height = null;
$age = null;
$firstName = null;
$lastName = null;
function __CONSTRUCT($firstName, $lastName)
{
//__CONSTRUCT is a special method that is called when the class is initialized
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
This is a valid (if not perfect) class when you use this code you'll first have to initailize an instance of the class which is like making of copy of it in a variable:
$steve = new person('Steve', 'Jobs');
Then when you want to change some property (not technicaly the correct word as there are no properties in PHP but just bear with me in this case I mean variable). We can access them like so:
$steve->age = 54;
Note: this assumes you are a little familiar with programming, which I guess you are.
A class is like a blueprint. Let's suppose you're making a game with houses in it. You'd have a "House" class. This class describes the house and says what can it do and what can be done to it. You can have attributes, like height, width, number of rooms, city where it is located, etc. You can also have "methods" (fancy name for functions inside a class). For example, you can have a "Clean()" method, which would tell all the people inside the house to clean it.
Now suppose someone is playing your game and clicks the "make new house" button. You would then create a new object from that class. In PHP, you'd write "$house = new House;", and now $house has all the attributes and methods of a class.
You can make as many houses as you want, and they will all have the same properties, which you can then change. For example, if the people living in a house decide to add one more room, you could write "$house->numberOfRooms++;". If the default number of rooms for a house was 4, this house would have 5 rooms, and all the others would have 4. As you can see, the attributes are independent from one instance to another.
This is the basics; there is a lot more stuff about classes, like inheritance, access modifiers, etc.
Now, you may ask yourself why is this useful. Well, the point of Object Oriented Programming (OOP) is to think of all the things in the program as independent objects, trying to design them so they can be used regardless of context. For example, your house may be a standalone variable, may be inside an array of houses. If you have a "Person" class with a "residence" attribute, then your house may be that attribute.
This is the theory behind classes and objects. I suggest you look around for examples of code. If you want, you can look at the classes I made for a Pong game I programmed. It's written in Python and may use some stuff you don't understand, but you will get the basic idea. The classes are here.
A class is essentially an abstraction.
You have built-in datatypes such as "int" or "string" or "float", each of which have certain behavior, and operations that are possible.
For example, you can take the square root of a float, but not of a string. You can concatenate two strings, or you can add two integers. Each of these data types represent a general concept (integers, text or numbers with a fixed number of significant digits, which may or may not be fractional)
A class is simply a user-defined datatype that can represent some other concept, including the operations that are legal on it.
For example, we could define a "password" class which implements the behavior expected of a password. That is, we should be able to take a text string and create a password from it. (If I type 'secret02', that is a legal password). It should probably perform some verification on this input string, making sure that it is at least N characters long, and perhaps that it is not a dictionary word. And it should not allow us to read the password. (A password is usually represented as ****** on the screen). Instead, it should simply allow us to compare the password to other passwords, to see if it is identical.
If the password I just typed is the same as the one I originally signed up with, I should be allowed to log in. But what the password actually is, is not something the application I'm logging in to should know. So our password class should define a comparison function, but not a "display" function.
A class basically holds some data, and defines which operations are legal on that data. It creates an abstraction.
In the password example, the data is obviously just a text string internally, but the class allows only a few operations on this data. It prevents us from using the password as a string, and instead only allows the specific operations that would make sense for a password.
In most languages, the members of a class can be either private or public. Anything that is private can only be accessed by other members of the class. That is how we would implement the string stored inside the password class. It is private, so it is still visible to the operations we define in the class, but code outside the class can not just access the string inside a password. They can only access the public members of the class.
A class is a form of structure you could think of, such as int, string and so forth that an instance can be made from using object oriented programming language. Like a template or blueprint the class takes on the structure. You write this structure with every association to the class. Something from a class would be used as an object instance in the Main() method where all the sysync programming steps take place.
This is why you see people write code like Car car = new Car();to draw out a new object from a class. I personally do not like this type of code, its very bad and circular and does not explain which part is the class syntax (arrangement). Too bad many programmers use this syntax and it is difficult for beginners to understand what they are perceiving.
Think of this as,
CarClass theCar = new CarClass(); //
The class essentially takes on the infinitely many forms. You can write properties that describe the CarClass and every car generated will have these. To get them from the property that "gets" what (reads) and "sets" what (writes) data, you simply use the dot operator on the object instance generates in the Main() and state the descriptive property to the actual noun. The class is the noumenon (a word for something like math and numbers, you cannot perceive it to the senses but its a thought like the #1). Instead of writing each item as a variable the class enables us to write a definition of the object to use.
With the ability to write infinitely many things there is great responsibility! Like "Hello World!" how this little first statement says much about our audience as programmers.
So
CarClass theCar = new CarClass(); //In a way this says this word "car" will be a car
theCar.Color = red; //Given the instance of a car we can add that color detail.
Now these are only implementations of the CarClass, not how to build one.
You must be wondering what are some other terms, a field, constructor, and class level methods and why we use them and indexing.
A field is another modifier on a property. These tend to be written on a private class level so nothing from the outside affects it and tends to be focused on the property itself for functionality. It is in another region where you declare it usually with an underscore in front of it. The field will add constraints necessary to maintain data integrity meaning that you will prevent people from writing values that make no sense in the context. (Like real like measurements in the negative... that is just not real.)
The Constructor
The easiest way to describe a constructor is to make claims to some default values on the object properties where the constructor scope is laid. In example a car has a color, a max speed, a model and a company. But what should these values be and should some be used in millions of copies from the CarClass or just a few? The constructor enables one to do this, to generate copies by establishing a basic quality. These values are the defaults assigned to a property in a constructor block. To design a constructor block type ctor[tab][tab]. Inside this simply refer to those properties you write above and place an assigned value on it.
Color = “Red”;
If you go to the main() and now use the car.Color property in any writing output component such as a the console window or textbox you should see the word “Red”. The details are thus implicit and hidden. Instead of offering every word from a book you simply refer to the book then the computer gets the remaining information. This makes code scripts compact and easy to use.
The Class level method should explain how to do some process over and over. Typically a string or some writing you can format some written information for a class and format it with placeholders that are in the writing to display that are represented with your class properties. It makes sense when you make an object instance then need to use the object to display the details in a .ToString() form. The class object instance in a sense can also contain information like a book or box. When we write .ToString() with a ToString override method at class level it will print your custom ToString method and how it should explain the code. You can also write a property .ToString() and read it. This below being a string should read fine as it is...
Console.Writeline(theCar.Color);
Once you get many objects, one at a time you can put them in a list that allows you to add or remove them. Just wait...
Here's a good page about Classes and Objects:
http://ficl.sourceforge.net/oo_in_c.html
This is a resource which I would kindly recommend
http://www.cplusplus.com/doc/tutorial/
not sure why, but starting with C++ to apply OOP might be natural prior of any other language, the above link helped me a lot when I started at least.
Classes are a way programmers mark their territory on code.
They are supposedly necessary for writing big projects.
Linus and his team must have missed that memo developing the linux kernel.
However, they can be good for organization and categorizing code I guess.
It makes it easier to navigate code in an ide such as visual studio with the object browsers.
Here are some usage demonstrations of classes in 31 languages on rosettacode
First of all back to the definitions:
Class definition:
Abstract definition of something, an user-type, a blueprint;
Has States / Fields / Properties (what an object knows) and Methods / Behaviors / Member Functions (what an object does);
Defines objects behavior and default values;
Object definition:
Instance of a Class, Repository of data;
Has a unique identity: the property of an object that distinguishes it from other objects;
Has its own states: describes the data stored in the object;
Exhibits some well defined behavior: follows the class’s description;
Instantiation:
Is the way of instantiate a class to create an object;
Leaves the object in a valid state;
Performed by a constructor;
To use a class you must instantiate the class though a contructor. In PHP a straight-forward example could be:
<?php
class SampleClass {
function __construct() {
print "In SampleClass constructor\n";
}
}
// In SampleClass constructor
$obj = new SampleClass ();
?>