Omnimaga

General Discussion => Technology and Development => Other => Topic started by: Ashbad on March 11, 2011, 01:53:04 pm

Title: Let's learn OOP!
Post by: Ashbad on March 11, 2011, 01:53:04 pm
many people out here on omnimaga are used to programming in asm, axe, and basic (possibly C) but not nearly as many have had experience with an object oriented programming language (OOPL) such as Java, C++, even some JS and Python.  Since this cripples people's ability to do advanced computer programming, or even higher level applications, I would like to set up this thread so that people can ask questions about it, and I can answer and post help articles.

Also, if I'm gonna make an OOP language for wither the prizm/CX, I might as well help others in the community learn basic/intermediate components of OOP -- since the langauge I'm developing adds even more advanced options onto Java's OOP system (the most powerful OOP system in my opinion) such as classgroups, multiple extensions, double extensions etc.

ask any questions here :)
Title: Re: Let's learn OOP!
Post by: merthsoft on March 11, 2011, 02:29:30 pm
Why do you say Java has the most powerful OOP system?
Title: Re: Let's learn OOP!
Post by: yunhua98 on March 11, 2011, 02:40:49 pm
Why do you say Java has the most powerful OOP system?

he says its just his opinion.  I may have misunderstood you, but Omnimaga's not a place for debating which language is the best.  ;)  Unless the topic is a poll to find out which is the community favorite.  ;)
Title: Re: Let's learn OOP!
Post by: Munchor on March 11, 2011, 02:51:50 pm
Why do you say Java has the most powerful OOP system?

Many languages derived from Java may have as good systems (C# for example).

But then again, not a place for debating languages.

Ashbad, I hope someone can use your help (who knows me :P).
Title: Re: Let's learn OOP!
Post by: merthsoft on March 11, 2011, 03:16:32 pm
Why do you say Java has the most powerful OOP system?

he says its just his opinion.  I may have misunderstood you, but Omnimaga's not a place for debating which language is the best.  ;)  Unless the topic is a poll to find out which is the community favorite.  ;)
I know he said it was his opinion, that's why I said "why do you say" not "why is". I'm simply asking him to elaborate on his opinion about a language that is directly related to the topic. He wants us to learn OOP, I want to learn what about Java OOP he thinks makes it the best. I'm not debating him, I'm asking him a question.
Title: Re: Let's learn OOP!
Post by: Munchor on March 11, 2011, 03:17:09 pm
Why do you say Java has the most powerful OOP system?

he says its just his opinion.  I may have misunderstood you, but Omnimaga's not a place for debating which language is the best.  ;)  Unless the topic is a poll to find out which is the community favorite.  ;)
I know he said it was his opinion, that's why I said "why do you say" not "why is". I'm simply asking him to elaborate on his opinion about a language that is directly related to the topic. He wants us to learn OOP, I want to learn what about Java OOP he thinks makes it the best. I'm not debating him, I'm asking him a question.

Nicely said, I hope Ashbad answers it.
Title: Re: Let's learn OOP!
Post by: yunhua98 on March 11, 2011, 03:18:15 pm
Why do you say Java has the most powerful OOP system?

he says its just his opinion.  I may have misunderstood you, but Omnimaga's not a place for debating which language is the best.  ;)  Unless the topic is a poll to find out which is the community favorite.  ;)
I know he said it was his opinion, that's why I said "why do you say" not "why is". I'm simply asking him to elaborate on his opinion about a language that is directly related to the topic. He wants us to learn OOP, I want to learn what about Java OOP he thinks makes it the best. I'm not debating him, I'm asking him a question.

kk, thats why I asked whether I misunderstood it.  ;)
Title: Re: Let's learn OOP!
Post by: ruler501 on March 11, 2011, 04:56:53 pm
I personally like python because it uses indentation instead of semicolons and braces. I find it easier to read.

This is a great thread. I always thought it would be nice too have someplavce to ask questions about features of OOP languages
Title: Re: Let's learn OOP!
Post by: AngelFish on March 11, 2011, 05:04:09 pm
  Since this cripples people's ability to do advanced computer programming, or even higher level applications, I would like to set up this thread so that people can ask questions about it, and I can answer and post help articles.

I disagree about low level languages crippling your ability to do high level work, but I'm still interesting in learning a bit about OOP.
Title: Re: Let's learn OOP!
Post by: ruler501 on March 11, 2011, 05:07:36 pm
I think there are some things you can do without OOP, but there are many things you need OOP for. At least in my opinion it would be much easier to use OOP then another kind of language.

I thought C/C++/C# were all OOP languages
<offtopic>has anyone heard of the languages D or GO?</offtopic>
Title: Re: Let's learn OOP!
Post by: Michael_Lee on March 11, 2011, 05:10:48 pm
I like how nobody has asked a question about OOP yet...

C isn't an OOP language, although C++ is.
Title: Re: Let's learn OOP!
Post by: Deep Toaster on March 11, 2011, 05:12:36 pm
I personally like python because it uses indentation instead of semicolons and braces. I find it easier to read.

Some of my opinions (and explanations) of OOP languages:

Python: I like Python because it's really, really intuitive. Like if you want to check if ELEMENT in LIST, that's exactly it -- if ELEMENT in LIST is valid syntax. It also supports dynamic typing, meaning you can represent a single variable in many different forms, which makes things really easy because you don't have to convert back and forth.

Java This is pretty much the OOP language, meaning it's the most strictly based on the concept of OOP. The entire structure of the language is based on OOPL as a foundation; everything you do will be tied in some way to the ideas of objects and classes. That makes it great for real-life applications, but if you want something simple that doesn't really need objects, Java's strict syntax requirements can be a minor PITA.

C++: C++ is great because it's actually compiled, straight to pure executable assembly (unlike Java, which compiles to bytecode that still needs to be interpreted).

I've never used C#, so can't give any tips here.
Title: Re: Let's learn OOP!
Post by: DJ Omnimaga on March 11, 2011, 06:01:41 pm
By the way, is Visual Basic 6.0 OOP?
Title: Re: Let's learn OOP!
Post by: Compynerd255 on March 11, 2011, 06:21:26 pm
EDIT: I realize that my sudden little OOP tutorial might have blown you guys away just a bit, seeing as no one has posted to this forum since I posted. I rewrote it a little bit.

Oh, an OOP thread! My base is in C#, which is an incredibly OOP language. I would be happy to answer any questions about OOP that you guys might have. In the meantime, I can tell you guys what the basic idea of OOP is:

In low level programming, everything is managed by the programmer. All of the objects in the game, and all of their properties, are handled directly by the programmer. For example, to define a spaceship with an X, Y, and rotation in TI-BASIC, and then move it 10 pixels forward, you would do something like:
Code: [Select]
0->X:0->Y:0->R
X+sin(R)*10->X:Y+cos(R)*10->Y

However, in OOP, all of the objects in a program are encapsulated in classes. A class is basically an object's definition, which contains all of the properties of an object. For example, in C#, you would say
Code: [Select]
class Ship
{
public int x;
public int y;
public float rotation;
}
to define the class called Ship, with integers x and y and a floating point number "rotation". The keyword public is a special keyword that means that other objects can mess with this value.
Within that class, you can add methods and subroutines, which do things to the ship's variables. For example, you can define this method within the definition of the Ship class:
Code: [Select]
public void Move(float amount)
{
X += Cos(Rotation) * amount;
Y += Sin(Rotation) * amount;
}

Once you have defined your Ship class, you can create a new instance of it, just like you would any other variable type (e.g. an integer or float). Then, later in the program, you can access its variables and call its subroutines. To reference a part of a class, first type the name you gave that particular instance of the object, then a period, and then the property you want to reference.
Code: [Select]
Ship ship = new Ship();
ship.rotation = Pi;
ship.Move(10);
Print(ship.x);
This piece of code creates a new instance of Ship, sets its rotation to Pi, moves it forward 10 pixels, and prints the ship's x-coordinate (which should now be -10).

Now, you might be asking: Why would I ever want to use this? There are two main reasons you would.
First, while it might be easier to manage one ship in low level programming, how about managing 100 of them? To track down all 300 variables, even in a list, would be unbearable, especially if you decided later that ships also need to have health or something. However, if you create a list of Ships, you can manage each ship individually.
Second, objects encapsulate things that you just don't want to manage, or want to protect somehow. For example, our Ship had a subroutine called Move on it to move the ship forward. Instead of having to remember sines and cosines every time a person wanted to move the ship, they could just set the rotation and movement amount and just say "Move". OOP also lets you hide variables that an object needs to know about, but not the rest of the game.

And objects have real-life applications as well, more so than in games. For example, you might want to create an object called CALCnet that manages calculator linking. By using this object, you don't have to worry about all of the little details and issues with CALCnet. All you have to do is start it up, shut it down, and tell it to send frames to people.

So, that's OOP 101. There is still a LOT more to the world of OOP, and I would be happy to share my knowledge.

EDIT: I realize that the sheer magnitude of this explanation might have scared you guys away. I hope I can be clearer and help you learn OOP.
Title: Re: Let's learn OOP!
Post by: DJ Omnimaga on March 15, 2011, 04:02:59 pm
It might be due to the post lenght. However I think it's good to bump the topic after a long while in case people miss it. Sometimes they might read half of it then continue later, but forget.
Title: Re: Let's learn OOP!
Post by: FinaleTI on March 15, 2011, 04:40:23 pm
I like it. It's a pretty good explanation, I think.
I learned OOP in Java for my AP class not all that long ago.
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 15, 2011, 04:56:46 pm
Yeah, it's a good explanation. :)
Java and C# are on pretty equal ground if we want to compare them.
Title: Re: Let's learn OOP!
Post by: Compynerd255 on March 15, 2011, 05:32:12 pm
I'm glad you like my explanation. What I wrote up there is just the surface of OOP. There are a lot of other cool topics you can learn about, such as:

Just let me know what you would like to know about, and I'll write a short explanation.
Title: Re: Let's learn OOP!
Post by: AngelFish on March 15, 2011, 05:43:39 pm
Now, you might be asking: Why would I ever want to use this? There are two main reasons you would.
First, while it might be easier to manage one ship in low level programming, how about managing 100 of them? To track down all 300 variables, even in a list, would be unbearable, especially if you decided later that ships also need to have health or something. However, if you create a list of Ships, you can manage each ship individually.
Second, objects encapsulate things that you just don't want to manage, or want to protect somehow. For example, our Ship had a subroutine called Move on it to move the ship forward. Instead of having to remember sines and cosines every time a person wanted to move the ship, they could just set the rotation and movement amount and just say "Move". OOP also lets you hide variables that an object needs to know about, but not the rest of the game.

And objects have real-life applications as well, more so than in games. For example, you might want to create an object called CALCnet that manages calculator linking. By using this object, you don't have to worry about all of the little details and issues with CALCnet. All you have to do is start it up, shut it down, and tell it to send frames to people.

I don't think I understand the purpose of OOP. Why would you use data abstraction and encapsulation for something like, to use your example, updating ships? Since you're presumably only manipulating a single ship at a time, wouldn't it be more logical to maintain an array of data about all ships. The data about that ship could be loaded into the variables you're manipulating and then reloaded into the array when you're done. It could actually work out very easily if you use "pointers" to the data in the array and a simple subroutine to manipulate the pointers and simultaneously updating the data in the array. It seems like encapsulating the ship data just pushes the mechanics of the program onto the interpreter/compiler. That certainly makes things easier to manage, but computers also have a tendency to write less efficient code than humans.

Also, I genuinely don't understand why you would want local variables. Doesn't that make things confusing when the variable "ShipSpeed" is used differently by three different subroutines? Plus, the OS/program has to maintain a table of all of the local variables, look them up, retrieve them from memory, and swap the appropriate ones in when necessary. That's not a lot of overhead, but it might not be suitable for high speed applications. It would also appear to be less memory efficient than maintaining global variables and being careful not to modify them.

PS: Your "Calcnet" example seems to be similar to calling another program or subroutine.
Title: Re: Let's learn OOP!
Post by: Compynerd255 on March 15, 2011, 06:07:31 pm
I don't think I understand the purpose of OOP. Why would you use data abstraction and encapsulation for something like, to use your example, updating ships? Since you're presumably only manipulating a single ship at a time, wouldn't it be more logical to maintain an array of data about all ships. The data about that ship could be loaded into the variables you're manipulating and then reloaded into the array when you're done. It could actually work out very easily if you use "pointers" to the data in the array and a simple subroutine to manipulate the pointers and simultaneously updating the data in the array. It seems like encapsulating the ship data just pushes the mechanics of the program onto the interpreter/compiler. That certainly makes things easier to manage, but computers also have a tendency to write less efficient code than humans.

Also, I genuinely don't understand why you would want local variables. Doesn't that make things confusing when the variable "ShipSpeed" is used differently by three different subroutines? Plus, the OS/program has to maintain a table of all of the local variables, look them up, retrieve them from memory, and swap the appropriate ones in when necessary. That's not a lot of overhead, but it might not be suitable for high speed applications. It would also appear to be less memory efficient than maintaining global variables and being careful not to modify them.

PS: Your "Calcnet" example seems to be similar to calling another program or subroutine.
First, as my example shows, if you don't use OOP programming, you would simply keep a multidimensional array of all of the properties of each of the ships. Now, if you have already defined what you want the ship to do, that's fine. But what if you want to add a property to the ship? You would have to change all of your array offsets to fit the new ship! However, if you instead kept an array of Ships, then adding a property isn't a problem.

Private variables are another important thing. For the Ship class, we don't really need any local variables. A better example of where you would need private variables is in a networking class. You don't want to have to tell the program to connect to such and such a port or use such and such a timeout. But the network class needs to know about these things. So, when you write the networking class, all of the little details are hidden from you, so all you have to worry about is doing things with the network. Private variables also prevent you from making foolish mistakes, like modifying variables you shouldn't be.

Also, what classes help us do is make code more portable and mobile. In non-OOP, a lot of pieces of code are interweaved and hard to seperate when you want to use them somewhere else. If you use OOP right, you can take that class into another application and use it again. For example, you might have a method that draws all of the game objects to the screen. However, if you are developing for multiple problems, you might want multiple "DrawTool" classes that respond to different protocols (e.g. one that draws on an 89, one that draws on an old PC, and one that draws on an XBox).
Title: Re: Let's learn OOP!
Post by: Ashbad on March 15, 2011, 07:28:52 pm
I love his explanation, was more well thought out than mine ^-^

Well then, maybe I should introduce inheritance?

What is inheritance?  speaking in vague terms, it's the relations between classes.  In example: let's say you have a quadrilateral class, but then you say 'Oh my, what if I want to relate shapes such as squares and rhombuses that are quadrilaterals but with special ways to calculate their areas and perimeters and such?  No probs -- this is where inheritance can be our friend ;)

You see, think of it like this:  All squares are quadrilaterals, but are all quadrilaterals squares?  Usually not.  So, they share many features such as 4 sides, a total of 360 degrees in internal angles sum, and such.  But squares have some other things that define them:  All sides are equal (always), all angles are Right angles, all lines are perpendicular, Area is S^2, etc.  So, how can we make the square inherit some of these basic qualities from class quadrilateral?  By declaring it a subclass!

Code: (Java) [Select]
public class Square extends Quadrilateral {
  private int[] sideLengths;
  private float[] angles;
 
  public void Square(float sideLength) {
    sideLengths = new int[4] = { sideLength, sideLength, sideLength, sideLength,};
    angles = new float[4] = { 90.0f, 90.0f, 90.0f, 90.0f};
  }

  @override
  public int Area() {
    return sideLengths[0]^2;
  }
}

As you can see, this class now extends class Quadrilateral.  Also, pretend class quadrilateral contains a Area() method that returns the area of the figure.  This is where a new thing comes in: @override.  While this is (usually) only found in Java (EDIT: I mean the @override operator, not the fact of overriding, which is actually found in almost all OOP languages), it just denotes an overriding of a super's method.  Now, if you don't understand half of the terms I just said, that's fine.  Here's a list.  Go study it for 3 hours:

- Super: refers to the class that is the superclass of the one you're working in.  In this example, class Quadrilateral.
- Overriding methods:  When you extend a class to another one, you inherit all of the methods that the super contained (besides the constructor, which actually can be overridden, but don't worry about that now.)  When you override the method, you make the method do something specific to your sub class -- in this case, instead of working a long formula to calculate the polygon's area, you can simply calculate one of the side's length squared.

[will continue later, gotta eat >.<]
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 15, 2011, 07:45:03 pm
Encapsulation and polymorphism (along with inheritance) are probably the key features of OOP. They make your code modular, flexible, extensible, and many other things.
Encapsulation (namely private variables) allows you to ignore the inner workings of another class/object and use the methods it provides. It frees you from having to deal with all the underlying things directly (like the networking and display examples) and allows delegation of tasks.
Polymorphism and inheritance also allow a common interface to classes. Example (Java):
Code: [Select]
abstract class IntegerOperation {
    public abstract int selfOperation();
    public abstract int binaryOperation(int otherArgument); //"abstract" just means that I'm not defining these methods
}
//IntegerOperation is a class that names two methods, selfOperation() and binaryOperation(int), that both return an int
//It is extended twice here:
class IncrementAdd extends IntegerOperation {
    public int number;
    public int selfOperation() {
        return number+1;
    }
    public int binaryOperation(int otherArgument) {
        return number+otherArgument;
    }
}
//Also here:
class DecrementSubtract extends IntegerOperation {
    public int number;
    public int selfOperation() {
        return number-1;
    }
    public int binaryOperation(int otherArgument) {
        return number-otherArgument;
    }
}
//And the main code here:
public class Main {
    public static void main(String[] args) {
        IntegerOperation intOp = new IncrementAdd();
        intOp.number = 5;
        System.out.println(intOp.selfOperation()); //Prints 6
        intOp = new DecrementSubtract();
        intOp.number = 20;
        System.out.println(intOp.binaryOp(13)); //Prints 7
    }
}
So, despite the two methods having different definitions in the two classes, we can use each as an IntegerOperation and invoke its methods. Yay polymorphism! :)
Note: And yeah, we're trying to sell you OOP :P
Edit: And this was written before Ashbad's post. It demonstrates inheritance and polymorphism.
Title: Re: Let's learn OOP!
Post by: Ashbad on March 15, 2011, 07:55:43 pm
yay polymorphism!  good addition to the thread, I must say ^-^ very nice indeed :)

This is one of the more complex and hard to learn portions of OOP, so it's fine if you people who are learning as we post along don't get it yet.  You will.  Oh yes, you will.
Title: Re: Let's learn OOP!
Post by: Binder News on March 15, 2011, 08:11:58 pm
I'll take a stab at Dynamic Memory.

Lets say you need to have a bunch of Contacts for your email account. Obviously, you don't know at compile-time how many Contacts the user will have.
With OOP, I can just say:
Code: [Select]
ArrayList<ContactInfo> contacts = new ArrayList<ContactInfo>();
for (int i=0; i<(# of contacts); i++)
{
    contacts.add(new ContactInfo(name,email,phoneNumber));
}
An ArrayList automatically changes its size when you add or remove objects. I could create 100 Contacts or 5, and it wouldn't matter.
I can also insert one in the middle with ease. Wouldn't that be a nightmare in ASM? :)
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 15, 2011, 08:15:48 pm
Binder hinted at them, so who wants to do generics? ;D
Binder: just a personal preference, but I would declare contacts as a List<ContactInfo> (obviously it's still an ArrayList<ContactInfo>, but it encourages you to type your methods and other code for the more generic List<ContactInfo> (and it lets you quickly swap ArrayList<> for another type of List<> if need be). Others may differ.
Title: Re: Let's learn OOP!
Post by: Binder News on March 15, 2011, 08:22:37 pm
I know, I was just keeping it simple. I'll take generics as well.

Generics give you the ability to write code to handle a wide range of problems.
Instead of having to make one array class for Dogs, one for Cats, and one for Birds, I can just do:
Code: [Select]
List<Dog> = new ArrayList<Dog>();
List<Cat> = new ArrayList<Cat>();
List<Bird> = new ArrayList<Bird>();
All I have to do is change two words, and it will take care of all the details. :)
It won't even let me put a Dog into a List of Cats. Why? They aren't the same type. :)
THAT would be hard in ASM (the type-checking I mean).

...

Or maybe not. But it's still a lot less code. :)

Title: Re: Let's learn OOP!
Post by: Ashbad on March 15, 2011, 08:23:45 pm
I see you used the Diamond operator there ^-^ a Java exclusive, so methinks.  I think I might as well explain that too :)

you see, the diamond operator basically adds General Types to a class that can be defined during instantiation.  This is actually something I learned on my own today with the Java tutorials!! w00t.  I'm a fast learning learner mesothinks.

Anyways, this is defined as the practice of Generics.  Basically, they can do a numbar of things to assist in the instantiation of classes and defining in a more specific way what exactly the class describes.  The <> operator is used to denote the generics associated with that class.  Like so:

Code: (Java) [Select]
public class Generics<T> {
  private T t;
  public void Generics() {
    t = new T();
  }
}

this sets up a class so that it will accept a generic, T, to fill in the spots denoted by T.  You can even think of it as a 'variable' for a currently undefined type of class.  Let's call the class here:

Code: (Java) [Select]
Generics<Lobstar> blueLobster = new blueLobster<Lobstar>();
this would make the instance blueLobster have a class framework that looks like this:

Code: (Java) [Select]
public class Generics<Lobstar> {
  private Lobstar t;
  public void Generics() {
    t = new Lobstar();
  }
}

as you can see, this can be very useful in a variety of applications - especially in a case like binder's where you can create a list of a Generic type, and the type can be of your choosing at instantiation.

I know it's rough, but it's not an easy topic to learn x.x  especially the advanced features I purposely left out because I'm still self-learning them.
Title: Re: Let's learn OOP!
Post by: uberspire on March 15, 2011, 08:33:13 pm
I see you used the Diamond operator there ^-^ a Java exclusive, so methinks.  I think I might as well explain that too :)
Java uses the diamond operator for generics, which came from C++'s usage of the diamond operator for templates. Perl also has a diamond operator, however it's used differently.
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 15, 2011, 08:36:59 pm
An example generic class, with two methods, display() and setThing(T):
Code: [Select]
class GenericClass<T> { //T stands for a certain class. Could be anything.
    public T thing;
    public void display() {
        System.out.println(thing.toString());
    }
    public void setThing(T thing) {
        this.thing = thing; //this.thing refers to the thing in this object, not the argument thing
}
public class Main {
    public static void main(String[] args) {
        GenericClass<String> test = new GenericClass<String>();
        test.setThing("Hello World!");
        test.display();
        GenericClass<Object> test2 = new GenericClass<Object>();
        test.setThing(new Object());
        test.display();
    }
}
So we use GenericClass in two ways: one where T is String, the other where T is Object. When you do that, you can pretty much pretend that all the T's in the class definition were replace with either String or Object. :) setThing(T) works as either setThing(String) or setThing(Object) depending on whether the object is a GenericClass<String> or GenericClass<Object>.
Generics are extremely powerful, and C#, C++, Java, and possibly others have them.
Edit: Is it really called the diamond operator? Also, aren't generics like templates?
Title: Re: Let's learn OOP!
Post by: Binder News on March 15, 2011, 08:38:18 pm
Time for another mini-lesson. The topic: Run-Time Type Information (RTTI)

So let's say you made this awesome editor for something. Now you want to allow people to write PLUGINS for it.
But oh noes, you wrote it in C++. Kinda tricky adding this in later, isn't it? You'll have to have some way for the editor to load plugin, DYNAMICALLY!
So, I could place Suzie's plugin in the plugins folder, and Bob's, and it would find them both and load them. But what if you change the API, or something. And how will you load the DLL?
Easy with Java/C#. Because they are compiled into ASM at RUNTIME, any libraries can be found, compiled, and used at RUNTIME! All you have to do is load the class file, and you can use the class. Also, if the plugin was built against an API, the API will be available because the API libraries/program was the first thing to be loaded. A great example is Bukkit (http://bukkit.org).
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 15, 2011, 08:40:19 pm
Something I forgot to mention about generics: You can have more than one generic type. An example would be Dictionary<K, V>.
Title: Re: Let's learn OOP!
Post by: qazz42 on March 15, 2011, 09:09:19 pm
Hmm, for C# my tips are keep your classes (when instantiating as I have a habit of doing, ALOT) clean and make sure vars and methods and such do not get mixed up (Method overloading (something I myself dislike doing, but I am just lazy) and making important vars private vars shall help you with this `-`)

Random other things I can think of are

1. Use Constructors/destructors to your advantage
2. Deirving from System.Windows.Forms is something you will do alot for GUI programs `-`

Eh, some of these are probably wrong, but they are what I do while programming in C#


EDIT: as I have never even touched Java, I probably just mentioned stuff you Java people know, beats me  :hyper:
Title: Re: Let's learn OOP!
Post by: Compynerd255 on March 16, 2011, 10:41:12 am
The Diamond operator (<>) is in C# as well, and it is used the same way. Also, C# does have a lot of Java's mechanics, but they are written differently (e.g. public class Square extends Quadrilateral is written as public class Square : Quadrilateral but it has the same function).

Here's another topic I want to write about: properties! Properties are a more elementary item in OOP, and their purpose is simply to set conditions or hook functions into the getting and setting of variables.

A generic Property is a block with special get and send methods, as shown below (in C#):
Code: [Select]
int foo;
public int Foo {
 get { return foo; }
 set { foo = value; }
}
Then, when objects reference the class, they reference the property Foo, which gets and sets foo.

Now, let's set some conditions on access to Foo (these are all within the definition of Foo):
Code: [Select]
get { return foo; }
private set { foo = value; }
This makes it so that outside forces referencing the object cannot set the value of Foo, only read it.

Code: [Select]
get { return foo; }
set { if (value < 100) foo = value; }
This restricts the value of Foo to values less than 100.

Code: [Select]
get { return foo; foo = 0; }
set {
 foo = value;
 RickRoll();
}
This code sets foo to zero after its value is read, and also calls the method RickRoll when foo is set.

Properties don't even have to be inimately attached to specific variables. For example:
Code: [Select]
public int Area {
get { return width*height; }
}
When the property Area is read, it will always return width * height;

Some advice on using Properties:
1. If you are just going to do a public Get and Set method with no restrictions, just declare a lone, public variable. It's faster.
2. Never make get less accessible than set. You won't be able to set it relative to itself.
3. Capitalize the names of public members, and leave private members as lowercase. This will help you seperate the two.
4. Use properties. Realize their sheer power!
Title: Re: Let's learn OOP!
Post by: calcdude84se on March 16, 2011, 10:35:03 pm
Java has no built-in syntax for properties, so things work slightly differently. You have to declare two methods, one for getting (typically called "get{variable}()" or "is{variable}()" for booleans), and one for setting (Typically "set{variable}()").
An example:
Code: [Select]
class Properties {
    private int property_;
    public int getProperty() {
        return property_;
    }
    private void setProperty(int property) {
        property_ = property;
    }
}
Of course, you would probably check values or other things, like compynerd said. But that's the basic outline. (Note that setProperty(int) is private. You can do anything with these that you can with other methods, because they are methods. ;))
Title: Re: Let's learn OOP!
Post by: Juju on March 16, 2011, 10:55:38 pm
Code: [Select]
get { return foo; foo = 0; }
set {
 foo = value;
 RickRoll();
}
This code sets foo to zero after its value is read, and also calls the method RickRoll when foo is set.
I'm not sure if foo = 0; gets executed after a return...

3. Capitalize the names of public members, and leave private members as lowercase. This will help you seperate the two.
I got taught to prefix m_ in front of private members instead of the lowercase thing, it's more readable.
Title: Re: Let's learn OOP!
Post by: Compynerd255 on March 17, 2011, 10:33:32 am
Code: [Select]
get { return foo; foo = 0; }
set {
 foo = value;
 RickRoll();
}
This code sets foo to zero after its value is read, and also calls the method RickRoll when foo is set.
I'm not sure if foo = 0; gets executed after a return...
Oops, you're right. I overlooked that. However, the set method will still RickRoll you. Oh, and here's a better example of something you could do in the set method:
Code: [Select]
set {
 foo = value;
 if (foo > 9000)
 Console.Writeline("It's over 9000!");
}
This writes "It's over 9000!" to the console (DOS) window whenever foo is set to a value over 9000.