My relative is studying programming and has a hard time understanding classes. He has trouble understanding for example that you need to instantiate it, that methods cannot access variables in other methods and if you change a variable in one instance of a class it doesn't change for other instances.
我的亲戚正在学习编程,很难理解课程。他很难理解,例如你需要实例化它,方法不能在其他方法中访问变量,如果你在类的一个实例中更改变量,它对其他实例不会改变。
I've tried to use analogies like a class definition is like a blueprint of a house. And instances are houses made from that blueprint.
我试图使用像类定义这样的类比就像一个房子的蓝图。实例是由该蓝图制成的房屋。
How do you explain classes and OO in general?
你如何解释一般的课程和面向对象?
17 个解决方案
#1
20
Seriously use Animals, it works great. And that's what nailed the concept for me years ago. Just found this C# code. It seems good
认真使用动物,效果很好。这就是多年前为我设计这个概念的原因。刚刚找到了这个C#代码。看起来不错
// Assembly: Common Classes
// Namespace: CommonClasses
public interface IAnimal
{
string Name
{
get;
}
string Talk();
}
// Assembly: Animals
// Namespace: Animals
public class AnimalBase
{
private string _name;
AnimalBase(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
}
// Assembly: Animals
// Namespace: Animals
public class Cat : AnimalBase, IAnimal
{
public Cat(String name) :
base(name)
{
}
public string Talk() {
return "Meowww!";
}
}
// Assembly: Animals
// Namespace: Animals
public class Dog : AnimalBase, IAnimal
{
public Dog(string name) :
base(name)
{
}
public string Talk() {
return "Arf! Arf!";
}
}
// Assembly: Program
// Namespace: Program
// References and Uses Assemblies: Common Classes, Animals
public class TestAnimals
{
// prints the following:
//
// Missy: Meowww!
// Mr. Bojangles: Meowww!
// Lassie: Arf! Arf!
//
public static void Main(String[] args)
{
List<IAnimal> animals = new List<IAnimal>();
animals.Add(new Cat("Missy"));
animals.Add(new Cat("Mr. Bojangles"));
animals.Add(new Dog("Lassie"));
foreach(IAnimal animal in animals)
{
Console.WriteLine(animal.Name + ": " + animal.Talk());
}
}
}
And once he's got this nailed, you challenge him to define Bird (fly), and then Penguin (fly!?)
一旦他得到了这个钉子,你挑战他定义鸟(飞),然后企鹅(飞!)
#2
20
The best way I got it through to my wife (a chartered accountant) is as follows.
我通过我的妻子(特许会计师)获得的最佳方式如下。
In 'regular' programming you have data (things that are manipulated) and code (things that manipulate) and they're separate. Sometimes you get mixed up because a certain piece of code tries to manipulate the wrong thing.
在“常规”编程中,您拥有数据(被操纵的东西)和代码(操作的东西),它们是分开的。有时你会混淆,因为某段代码试图操纵错误的东西。
In my wife's case, I said a invoice arrived (which involves no physical money changing hands) and accidentally updated a bank balance, something she immediately saw as potential fraud (she used to do forensic accounting, everything is potential fraud to her, including most of my share trades :-).
在我妻子的情况下,我说收到发票(没有实物转手),并且不小心更新了银行存款,她立即认为这是潜在的欺诈行为(她曾经做过法务会计,一切都是潜在的欺诈行为,包括大多数我的股票交易:-)。
You could just as easily say that a piece of code meant to wash a floor with a huge mop decided to do it with your toothbrush.
你可以很容易地说,用一把巨大的拖把清洗地板的一段代码决定用你的牙刷来做。
With OO programming, the manipulators and manipulatees are inextricably entwined. You don't apply the floor washing process to the floor, instead you command the floor to wash itself. It knows how to do this because the code is part of the object, not something external to it.
通过OO编程,操纵器和操纵器不可避免地缠绕在一起。您不要将地板清洗过程应用到地板上,而是指示地板自行清洗。它知道如何执行此操作,因为代码是对象的一部分,而不是外部的代码。
In the accounting case above, I think we ended up having the chart of accounts as the object and we told it to apply a invoice to itself. Since it understood the process, it knew which accounts were allowed to be updated (creditors liability account and an expense account if I remember correctly).
在上面的会计案例中,我认为我们最终将会计科目表作为对象,并且我们告诉它将发票应用于自身。由于它了解这个过程,它知道允许更新哪些帐户(债权人责任帐户和费用帐户,如果我没记错的话)。
Anyway, that's irrelevant and I'm just meandering now. What I'm saying is to express it in terms your target audience will understand. I suppose that's the secret of most teaching.
无论如何,这是无关紧要的,我现在只是在蜿蜒。我所说的是用目标受众理解的术语来表达它。我想这是大多数教学的秘诀。
#3
8
Like all old farts, I'd like to answer this with a story from my own life.
像所有老屁一样,我想用自己生活中的故事回答这个问题。
I started programming basic on a VIC-20. Not knowing anything else, I though this was how all computers were programmed. I thought it was a bit hard to keep track of which variable names I had used and which were still free, (scope problem). I also thought it was hard to divide my program into repeatable chunks using gosub-return and setting and reading the variables that these would use, (lack of methods).
我开始在VIC-20上编程基础。不知道其他什么,我虽然这是所有计算机的编程方式。我认为跟踪哪些变量名称以及哪些变量仍然是免费的(范围问题)有点困难。我还认为很难将我的程序划分为可重复的块,使用gosub-return并设置和读取这些将使用的变量(缺少方法)。
Then I got into Turbo C over MS-DOS. Now I could create my own methods and functions! I was no longer stuck with the old finite set of commands in basic. I felt like I was creating a new language for every program I wrote. C gave me more expressive power.
然后我通过MS-DOS进入Turbo C.现在我可以创建自己的方法和功能!我不再困在基本的旧有限命令集中。我觉得我正在为我写的每个程序创建一种新语言。 C给了我更多表现力。
C++ was the first object oriented language I heard about. The big moment for me was when I understood that I could create my own data types, and even overload the operators. Again, it felt like I could create my own language containing both new functions and data types, complete with operators.
C ++是我听说过的第一个面向对象的语言。对我而言,最重要的时刻是我明白我可以创建自己的数据类型,甚至超载运算符。同样,我觉得我可以创建自己的语言,包含新的功能和数据类型,以及运算符。
That's how I would sell OO to a new programmer. Explain that it gives expressive power because they can define their own data types. I always thought encapsulation was a better selling point than inheritance.
这就是我如何向新的程序员出售OO。说明它具有表达能力,因为它们可以定义自己的数据类型。我一直认为封装是比继承更好的卖点。
#4
4
I second the 'Animal' approach!
我是第二个'动物'方法!
This little article on JavaRanch, "How my Dog learned Polymorphism" helped me a lot (it's pretty much language independent):
这篇关于JavaRanch的小文章,“我的狗如何学习多态性”对我帮助很大(它几乎与语言无关):
#5
3
While you are explaining OO with animals, do not forget to illustrate the "is-a" relationship with Stinger missiles-armed kangaroos ;-)
当你用动物解释OO时,别忘了用Stinger导弹武装的袋鼠来说明“is-a”关系;-)
The kangaroos scattered, as predicted, and the Americans nodded appreciatively . . . and then did a double-take as the kangaroos reappeared from behind a hill and launched a barrage of stinger missiles at the hapless helicopter. (Apparently the programmers had forgotten the remove "that" part of the infantry coding).
正如预测的那样,袋鼠分散了,美国人赞赏地点了点头。 。 。随着袋鼠从山后重新出现并在倒霉的直升机上发射了一连串的毒刺导弹,然后进行了双重拍摄。 (显然,程序员已经忘记了移除步兵编码的“那部分”)。
The lesson? Objects are defined with certain attributes, and any new object defined in terms of the old one inherits all the attributes. The embarrassed programmers had learned to be careful when reusing object-oriented code, and the Yanks left with the utmost respect for the Australian wildlife.
课程?使用某些属性定义对象,并且根据旧属性定义的任何新对象都会继承所有属性。尴尬的程序员在重用面向对象的代码时学会了小心,并且Yanks最为尊重澳大利亚野生动物。
#6
3
I assume the target knows how to use graphical user interfaces. I found the best way is to describe OOP with stuff that they are really used for. Say
我假设目标知道如何使用图形用户界面。我发现最好的方法是用他们真正用过的东西来描述OOP。说
Class
A Window is a class. It has methods like
窗口是一个类。它有像这样的方法
- Show a window
- Enable a window
- Set the window's title
显示一个窗口
启用一个窗口
设置窗口的标题
A Window has attributes. That is data associated with it. It is encapsulated into the class, together with the functions that operate on them
窗口具有属性。那是与之相关的数据。它被封装到类中,以及对它们进行操作的函数
- A Window has dimensions. Width and height.
- A Window has possibly a parent window, and possibly children.
- A Window has a title
窗口有尺寸。宽度和高度。
窗口可能有父窗口,可能还有子窗口。
一个窗口有一个标题
Object
There are many windows. Each particular window is an object of the class Window. A Parent window containing 10 windows makes 11 Window objects.
有很多窗户。每个特定窗口都是Window类的对象。包含10个窗口的父窗口生成11个Window对象。
Deriveration
A Button is a Window. It has dimensions has a parent window and has a title, the label of a button. It's a special kind of a window. When you ask for a window object, someone can give you a Button. A Button can add functions and data that are specific for a button:
按钮是一个窗口。它有维度有一个父窗口,并有一个标题,一个按钮的标签。这是一种特殊的窗口。当你要求一个窗口对象时,有人可以给你一个按钮。 Button可以添加特定于按钮的功能和数据:
- A Button has a state. It can be in a pressed state, and unpressed state.
- A Button can be the default button in a Window.
按钮有一个状态。它可以处于按压状态和未按下状态。
按钮可以是窗口中的默认按钮。
#7
#8
1
How about "each molding is built using a mold", or "each model is built using a template", and so "each object is built using a class" ?
如何“使用模具构建每个模具”,或“每个模型使用模板构建”,因此“每个对象是使用类构建的”?
Note that it works for class-oriented OOP (which is what you want), but not for prototype-oriented OOP.
请注意,它适用于面向类的OOP(这是您想要的),但不适用于面向原型的OOP。
As for explaining OOP to a programmer, I'd add examples illustrating:
至于向程序员解释OOP,我将添加一些示例说明:
Separating state from behavior
Most of the time, an instance describe a state, and a class describe a behavior.
大多数情况下,实例描述状态,类描述行为。
Delegation
An instance delegates its behavior to its class, and the class in turn can delegate its behavior to its superclasses (or mixins or traits)
实例将其行为委托给其类,然后该类可以将其行为委托给其超类(或mixins或traits)
Polymorphism
If class A inherits from class B, an instance of A can be used anywhere an instance of class B can be used.
如果A类继承自B类,则可以在任何可以使用B类实例的地方使用A的实例。
Messages & methods
A message (or generic function, or virtual function) is like a question. Most of the time, several classes can answer to this question.
消息(或通用函数或虚函数)就像一个问题。大多数时候,几个班级都可以回答这个问题。
A corresponding method is a possible answer to the question, that resides in a class.
相应的方法是问题的可能答案,它存在于一个类中。
When sending a message to an instance, the instance looks up for a corresponding method in its class. If found, it calls it (with the instance bound to 'self' or 'this'. Otherwise, it looks for a corresponding method in its mixins, traits, or superclasses, and calls it.
向实例发送消息时,实例会在其类中查找相应的方法。如果找到,则调用它(实例绑定到'self'或'this'。否则,它会在其mixins,traits或superclasses中查找相应的方法,并调用它。
#9
1
If they're old enough to have ever filled out a tax form, show them a 1040EZ and explain that an instance of a class is like a filled-out form: each blank is a member variable of the object, and the form also includes instructions for what to do with the member variables, and those instructions are the member functions of the object. A class itself is like a master copy of the form, from which you can print off an endless number of blank forms to fill out.
如果他们已经足够大,可以填写税表,请向他们展示1040EZ,并解释一个类的实例就像一个填写的表单:每个空白是对象的成员变量,表单还包括如何处理成员变量的说明,这些指令是对象的成员函数。类本身就像是表单的主副本,您可以从中打印出无数个空白表单来填写。
One thing that I would counsel to AVOID in trying to communicate the concepts of OO to new programmers is using only examples where objects (in the OO sense) represent real-world physical objects. This will actually make students more confused when they encounter objects used to represent non-physical objects (such as a color scheme, or most of the behavioral patterns in "Design Patterns") or objects used just as a useful way to store related functions and related data in the same place (think Java's java.lang.Math for an example.)
在尝试将OO的概念传达给新程序员时,我会建议AVOID的一件事是仅使用对象(在OO意义上)代表现实世界的物理对象的示例。这实际上会让学生在遇到用于表示非物理对象的对象(例如颜色方案或“设计模式”中的大多数行为模式)或者仅用作存储相关功能的有用方法的对象时更加困惑。相关数据在同一个地方(以Java的java.lang.Math为例。)
#10
1
Believe it or not, sports!
信不信由你,体育!
I've had success in teaching and mentoring by talking about the way that e.g. a play for a football team is described in terms of how the various positions (Center, Quarterback, Runningback, etc.) interact to accomplish a particular goal. In one version, the positions correspond to classes, and specific persons (Tony Romo, Johnny Unitas, etc.) are instances of the class -- individuals who exhibit the same behaviors as defined by the positions.
我通过谈论如下的方式在教学和辅导方面取得了成功。根据各种位置(中心,四分卫,跑卫等)如何相互作用来完成特定目标,描述了足球队的比赛。在一个版本中,职位对应于班级,特定人员(Tony Romo,Johnny Unitas等)是班级的实例 - 表现出与职位相同的行为的个人。
The second version of this metaphor is to explain that the positions may be interfaces (in the Java sense) rather than classes. An interface really represents a role fulfilled by any object that implements the methods of the interface. And it's perfectly reasonable for an object (via its class, in Java) to implement multiple interfaces, just as it is possible for a talented individual to play more than one position on a sports team.
这个比喻的第二个版本是解释位置可能是接口(在Java意义上)而不是类。接口实际上代表实现接口方法的任何对象所实现的角色。对于一个对象(通过它的类,用Java)来实现多个接口是完全合理的,就像一个有才能的人可以在一个运动团队中扮演多个位置一样。
Finally, the play is like a pattern, in that it describes how a set of roles interact to accomplish some specific goal.
最后,该游戏就像一个模式,因为它描述了一组角色如何相互作用以实现某个特定目标。
#11
1
An object is a black box, which you can't see through. Public methods are buttons on them. Protected methods are buttons hidden on the bottom, private methods are dip switches inside.
一个物体是一个黑盒子,你无法看透。公共方法是它们上的按钮。受保护的方法是隐藏在底部的按钮,私有方法是在内部的dip开关。
Let's see a washer as an object. We don't know how it works. We don't care if it's powered by natural gas, diesel, electricity, or plutonium. However, the mechanism and internal structure will vary greatly depending on the energy source like a combustion engine is needed for some. We don't care as long as if we push a "Wash" button, it washes our clothes.
让我们看一个垫圈作为对象。我们不知道它是如何工作的。我们不关心它是否由天然气,柴油,电力或钚提供动力。然而,机械和内部结构将根据能源而变化很大,就像某些人需要内燃机一样。我们不在乎,只要我们按下“洗涤”按钮,它就会洗掉我们的衣服。
Let's turn the washer not Object-oriented. Expose all the buttons by arranging them on the top. Customers can now turbo-charge the engine by tweaking some dip switches. Make the chassis transparent. Now, you can see your energy-saving washing machine is actually hybrid-powered. There are some monkeys in it. You free them into the wild, and the machine eats up your utility bill like a gas-guzzler.
让我们把洗衣机变成面向对象的。将所有按钮排列在顶部,露出所有按钮。客户现在可以通过调整一些拨码开关对发动机进行涡轮增压。使机箱透明。现在,你可以看到你的节能洗衣机实际上是混合动力的。里面有一些猴子。你将它们释放到野外,机器就像一个耗油的人一样吃掉你的公用事业账单。
#12
0
Object-oriented programming is one technique of raising the level of abstraction by means of which the programmer communicates with the computer: from the level of flipping individual bits on and off, from the level of punching holes in paper cards, from the level of extraordinarily complex sequences of basic instruction codes, from the level of less complicated definitions of reusable templates for blocks of data and reusable blocks of code (structs and procedures), to the level of transcribing the concepts in the programmer's mind into code, so that what goes on inside the computer comes to resemble, for the programmer, what goes on outside the computer in the world of physical objects, intangible assets, and cause-and-effect.
面向对象编程是提高程序员与计算机通信的抽象级别的一种技术:从打开和关闭各个位的级别,从纸卡的打孔级别,从异常级别开始复杂的基本指令代码序列,从用于数据块的可重用模板的不太复杂的定义和可重用的代码块(结构和过程)的级别,到将程序员心中的概念转录为代码的级别,以便在计算机内部,对于程序员来说,在物理对象,无形资产和因果关系的世界中,计算机外部会发生什么。
#13
0
the best book i've ever on object-oriented programming is Betrand's "Object-Oriented Software Construction" - if you really want to get the basics, there is no way around it.
关于面向对象编程的最好的书是Betrand的“面向对象的软件构建” - 如果你真的想要获得基础知识,那么就无法解决它。
#14
0
I explain that procedural program is built around the "verbs" of the system, the things you want the system to do, whereas object-oriented programming is build about the "nouns," the things in the system, and what they are capable of, and that for many people this allows for a more straightforward mapping from the problem domain to software.
我解释说,程序程序是围绕系统的“动词”构建的,是系统要做的事情,而面向对象的程序设计则是关于“名词”,系统中的事物,以及它们的能力。 ,对于许多人来说,这允许从问题域到软件的更直接的映射。
For the example, I use cars -- "Honda Accord" is a class, whereas the vehicle sitting in the parking lot is an object, an instance of a Honda Accord. A Honda Accord is a sedan, which is a car, which is an automobile, which is a motorized vehicle, which is a mode of transportation, etc. I cannot do anything with a car until I have a physical car to work with -- it doesn't help me that the idea of a Honda Accord exists.
例如,我使用汽车 - “本田雅阁”是一类,而坐在停车场的车辆是一个物体,本田雅阁的一个例子。本田雅阁是一辆轿车,这是一辆汽车,是一种汽车,是一种机动车,这是一种交通工具等。在我有一辆实体车与之合作之前我无法做任何事情 - 本田雅阁的概念存在并不能帮助我。
It also helps for discussing interfaces and polymorphism -- the gas pedal means accelerate, regardless what the car does behind the scenes to make that happen. There are "private" parts of the car that I as user do not have access to -- I cannot directly apply an individual brake.
它还有助于讨论接口和多态性 - 加速踏板意味着加速,无论汽车在幕后做什么来实现这一点。我用户无法访问汽车的“私人”部件 - 我无法直接应用单独的制动器。
#15
0
Since the issue is to explain to a new programmer and not to a mother or a wife, I would go right straight to the point. OO is about three main concepts:
既然问题是要向新的程序员而不是母亲或妻子解释,我会直截了当地说明问题。 OO主要涉及三个主要概念:
- Inheritance: a dog is an animal, parent-child, is-a relationship test, etc.
- Encapsulation: public-private (protected), information hiding, internal underlying details are not important to the users of the class, protect users from future changes in the implementation.
- Polymorphism: run-time binding, late binding, method that gets invoked depends on the type of the object and not the reference or pointer to the object.
遗产:狗是动物,亲子,是关系测试等。
封装:公共 - 私有(受保护),信息隐藏,内部底层细节对类的用户并不重要,保护用户免受未来实施的变化。
多态性:运行时绑定,后期绑定,被调用的方法取决于对象的类型,而不是对象的引用或指针。
Also, depending on how much the new programmer has been doing a procedural language, I would need to help him/her unlearn that the functions or procedures are no longer central.
此外,根据新程序员使用程序语言的程度,我需要帮助他/她忘记函数或过程不再是中心。
#16
0
Games are good. There are gameobjects, from this walls, enemies and players inherit. The gameobjects should be renderable have collision-logic etc. The enemies have ai-logic while the player is keyboard controlled.
游戏很好。有游戏对象,从这些墙壁,敌人和玩家继承。游戏对象应该是可渲染的,具有碰撞逻辑等。当玩家受键盘控制时,敌人具有动态逻辑。
Some UI-elements are also good, there are buttons, inputboxes etc that all inherit from some baseobject that has code for managing mouse-events etc.
一些UI元素也很好,有按钮,输入框等都从一些baseobject继承,它们具有管理鼠标事件等的代码。
I don't like the animal-example because i've never seen a "real" program that has ever had to use of animals in that way. It will only make people use inheritance all over the place and you will end up with cubes inheriting from rectangles that inherit from lines (why does so many books insist on using this as example? ).
我不喜欢这个动物的例子,因为我从来没有见过曾经以这种方式使用过动物的“真实”程序。它只会让人们在整个地方使用继承,你最终会得到从行继承的矩形继承的多维数据集(为什么这么多书仍然坚持使用它作为例子?)。
#17
0
OOP is a higher level of abstraction, a programmer can't really come to grasp it unless he has a good understanding of the normal (read: procedural) way of programming, and he must be able to write some programs that do something useful.
OOP是一个更高级别的抽象,程序员无法真正掌握它,除非他非常了解正常(读取:程序)编程方式,并且他必须能够编写一些有用的程序。
For me it took a series of several lectures by one of my university profs, where he discussed many theoretical aspects of programming, he tried to convince us that programming is about manipulating data, and that this data is a representation of the "state(s)" of the program, and some other abstract stuff that I forgot now! But the point is, it's hard to understand OOP without some theoretical abstract discussion first, and this discussion wouldn't make any sense to a person who hadn't had experience writing some real code.
对我来说,我的一位大学教授参加了一系列的讲座,在那里他讨论了编程的许多理论方面,他试图说服我们编程是关于操纵数据,而这个数据是“状态”的表示。 )“该程序,以及我现在忘记的一些其他抽象的东西!但问题是,如果没有一些理论上的抽象讨论,首先很难理解OOP,而这种讨论对于没有经验编写实际代码的人来说没有任何意义。
After the theoretical discussion, you give an example of a moderately complex program, written in procedural style, and slowly convert it, step by step, into object oriented style. After the concrete example, you should go back to the theoretical discussion and just summarize the main points, directly relate the theoretical constructs to the concrete example, e.g you can talk about how the name, age, and salary of an employee represent his state.
在理论讨论之后,您举一个中等复杂程序的例子,用程序风格编写,然后逐步将其逐步转换为面向对象的风格。在具体的例子之后,你应该回到理论上的讨论,只是总结一下要点,直接将理论结构与具体的例子联系起来,例如,你可以谈谈一个雇员的姓名,年龄和工资如何代表他的国家。
#1
20
Seriously use Animals, it works great. And that's what nailed the concept for me years ago. Just found this C# code. It seems good
认真使用动物,效果很好。这就是多年前为我设计这个概念的原因。刚刚找到了这个C#代码。看起来不错
// Assembly: Common Classes
// Namespace: CommonClasses
public interface IAnimal
{
string Name
{
get;
}
string Talk();
}
// Assembly: Animals
// Namespace: Animals
public class AnimalBase
{
private string _name;
AnimalBase(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
}
// Assembly: Animals
// Namespace: Animals
public class Cat : AnimalBase, IAnimal
{
public Cat(String name) :
base(name)
{
}
public string Talk() {
return "Meowww!";
}
}
// Assembly: Animals
// Namespace: Animals
public class Dog : AnimalBase, IAnimal
{
public Dog(string name) :
base(name)
{
}
public string Talk() {
return "Arf! Arf!";
}
}
// Assembly: Program
// Namespace: Program
// References and Uses Assemblies: Common Classes, Animals
public class TestAnimals
{
// prints the following:
//
// Missy: Meowww!
// Mr. Bojangles: Meowww!
// Lassie: Arf! Arf!
//
public static void Main(String[] args)
{
List<IAnimal> animals = new List<IAnimal>();
animals.Add(new Cat("Missy"));
animals.Add(new Cat("Mr. Bojangles"));
animals.Add(new Dog("Lassie"));
foreach(IAnimal animal in animals)
{
Console.WriteLine(animal.Name + ": " + animal.Talk());
}
}
}
And once he's got this nailed, you challenge him to define Bird (fly), and then Penguin (fly!?)
一旦他得到了这个钉子,你挑战他定义鸟(飞),然后企鹅(飞!)
#2
20
The best way I got it through to my wife (a chartered accountant) is as follows.
我通过我的妻子(特许会计师)获得的最佳方式如下。
In 'regular' programming you have data (things that are manipulated) and code (things that manipulate) and they're separate. Sometimes you get mixed up because a certain piece of code tries to manipulate the wrong thing.
在“常规”编程中,您拥有数据(被操纵的东西)和代码(操作的东西),它们是分开的。有时你会混淆,因为某段代码试图操纵错误的东西。
In my wife's case, I said a invoice arrived (which involves no physical money changing hands) and accidentally updated a bank balance, something she immediately saw as potential fraud (she used to do forensic accounting, everything is potential fraud to her, including most of my share trades :-).
在我妻子的情况下,我说收到发票(没有实物转手),并且不小心更新了银行存款,她立即认为这是潜在的欺诈行为(她曾经做过法务会计,一切都是潜在的欺诈行为,包括大多数我的股票交易:-)。
You could just as easily say that a piece of code meant to wash a floor with a huge mop decided to do it with your toothbrush.
你可以很容易地说,用一把巨大的拖把清洗地板的一段代码决定用你的牙刷来做。
With OO programming, the manipulators and manipulatees are inextricably entwined. You don't apply the floor washing process to the floor, instead you command the floor to wash itself. It knows how to do this because the code is part of the object, not something external to it.
通过OO编程,操纵器和操纵器不可避免地缠绕在一起。您不要将地板清洗过程应用到地板上,而是指示地板自行清洗。它知道如何执行此操作,因为代码是对象的一部分,而不是外部的代码。
In the accounting case above, I think we ended up having the chart of accounts as the object and we told it to apply a invoice to itself. Since it understood the process, it knew which accounts were allowed to be updated (creditors liability account and an expense account if I remember correctly).
在上面的会计案例中,我认为我们最终将会计科目表作为对象,并且我们告诉它将发票应用于自身。由于它了解这个过程,它知道允许更新哪些帐户(债权人责任帐户和费用帐户,如果我没记错的话)。
Anyway, that's irrelevant and I'm just meandering now. What I'm saying is to express it in terms your target audience will understand. I suppose that's the secret of most teaching.
无论如何,这是无关紧要的,我现在只是在蜿蜒。我所说的是用目标受众理解的术语来表达它。我想这是大多数教学的秘诀。
#3
8
Like all old farts, I'd like to answer this with a story from my own life.
像所有老屁一样,我想用自己生活中的故事回答这个问题。
I started programming basic on a VIC-20. Not knowing anything else, I though this was how all computers were programmed. I thought it was a bit hard to keep track of which variable names I had used and which were still free, (scope problem). I also thought it was hard to divide my program into repeatable chunks using gosub-return and setting and reading the variables that these would use, (lack of methods).
我开始在VIC-20上编程基础。不知道其他什么,我虽然这是所有计算机的编程方式。我认为跟踪哪些变量名称以及哪些变量仍然是免费的(范围问题)有点困难。我还认为很难将我的程序划分为可重复的块,使用gosub-return并设置和读取这些将使用的变量(缺少方法)。
Then I got into Turbo C over MS-DOS. Now I could create my own methods and functions! I was no longer stuck with the old finite set of commands in basic. I felt like I was creating a new language for every program I wrote. C gave me more expressive power.
然后我通过MS-DOS进入Turbo C.现在我可以创建自己的方法和功能!我不再困在基本的旧有限命令集中。我觉得我正在为我写的每个程序创建一种新语言。 C给了我更多表现力。
C++ was the first object oriented language I heard about. The big moment for me was when I understood that I could create my own data types, and even overload the operators. Again, it felt like I could create my own language containing both new functions and data types, complete with operators.
C ++是我听说过的第一个面向对象的语言。对我而言,最重要的时刻是我明白我可以创建自己的数据类型,甚至超载运算符。同样,我觉得我可以创建自己的语言,包含新的功能和数据类型,以及运算符。
That's how I would sell OO to a new programmer. Explain that it gives expressive power because they can define their own data types. I always thought encapsulation was a better selling point than inheritance.
这就是我如何向新的程序员出售OO。说明它具有表达能力,因为它们可以定义自己的数据类型。我一直认为封装是比继承更好的卖点。
#4
4
I second the 'Animal' approach!
我是第二个'动物'方法!
This little article on JavaRanch, "How my Dog learned Polymorphism" helped me a lot (it's pretty much language independent):
这篇关于JavaRanch的小文章,“我的狗如何学习多态性”对我帮助很大(它几乎与语言无关):
#5
3
While you are explaining OO with animals, do not forget to illustrate the "is-a" relationship with Stinger missiles-armed kangaroos ;-)
当你用动物解释OO时,别忘了用Stinger导弹武装的袋鼠来说明“is-a”关系;-)
The kangaroos scattered, as predicted, and the Americans nodded appreciatively . . . and then did a double-take as the kangaroos reappeared from behind a hill and launched a barrage of stinger missiles at the hapless helicopter. (Apparently the programmers had forgotten the remove "that" part of the infantry coding).
正如预测的那样,袋鼠分散了,美国人赞赏地点了点头。 。 。随着袋鼠从山后重新出现并在倒霉的直升机上发射了一连串的毒刺导弹,然后进行了双重拍摄。 (显然,程序员已经忘记了移除步兵编码的“那部分”)。
The lesson? Objects are defined with certain attributes, and any new object defined in terms of the old one inherits all the attributes. The embarrassed programmers had learned to be careful when reusing object-oriented code, and the Yanks left with the utmost respect for the Australian wildlife.
课程?使用某些属性定义对象,并且根据旧属性定义的任何新对象都会继承所有属性。尴尬的程序员在重用面向对象的代码时学会了小心,并且Yanks最为尊重澳大利亚野生动物。
#6
3
I assume the target knows how to use graphical user interfaces. I found the best way is to describe OOP with stuff that they are really used for. Say
我假设目标知道如何使用图形用户界面。我发现最好的方法是用他们真正用过的东西来描述OOP。说
Class
A Window is a class. It has methods like
窗口是一个类。它有像这样的方法
- Show a window
- Enable a window
- Set the window's title
显示一个窗口
启用一个窗口
设置窗口的标题
A Window has attributes. That is data associated with it. It is encapsulated into the class, together with the functions that operate on them
窗口具有属性。那是与之相关的数据。它被封装到类中,以及对它们进行操作的函数
- A Window has dimensions. Width and height.
- A Window has possibly a parent window, and possibly children.
- A Window has a title
窗口有尺寸。宽度和高度。
窗口可能有父窗口,可能还有子窗口。
一个窗口有一个标题
Object
There are many windows. Each particular window is an object of the class Window. A Parent window containing 10 windows makes 11 Window objects.
有很多窗户。每个特定窗口都是Window类的对象。包含10个窗口的父窗口生成11个Window对象。
Deriveration
A Button is a Window. It has dimensions has a parent window and has a title, the label of a button. It's a special kind of a window. When you ask for a window object, someone can give you a Button. A Button can add functions and data that are specific for a button:
按钮是一个窗口。它有维度有一个父窗口,并有一个标题,一个按钮的标签。这是一种特殊的窗口。当你要求一个窗口对象时,有人可以给你一个按钮。 Button可以添加特定于按钮的功能和数据:
- A Button has a state. It can be in a pressed state, and unpressed state.
- A Button can be the default button in a Window.
按钮有一个状态。它可以处于按压状态和未按下状态。
按钮可以是窗口中的默认按钮。
#7
#8
1
How about "each molding is built using a mold", or "each model is built using a template", and so "each object is built using a class" ?
如何“使用模具构建每个模具”,或“每个模型使用模板构建”,因此“每个对象是使用类构建的”?
Note that it works for class-oriented OOP (which is what you want), but not for prototype-oriented OOP.
请注意,它适用于面向类的OOP(这是您想要的),但不适用于面向原型的OOP。
As for explaining OOP to a programmer, I'd add examples illustrating:
至于向程序员解释OOP,我将添加一些示例说明:
Separating state from behavior
Most of the time, an instance describe a state, and a class describe a behavior.
大多数情况下,实例描述状态,类描述行为。
Delegation
An instance delegates its behavior to its class, and the class in turn can delegate its behavior to its superclasses (or mixins or traits)
实例将其行为委托给其类,然后该类可以将其行为委托给其超类(或mixins或traits)
Polymorphism
If class A inherits from class B, an instance of A can be used anywhere an instance of class B can be used.
如果A类继承自B类,则可以在任何可以使用B类实例的地方使用A的实例。
Messages & methods
A message (or generic function, or virtual function) is like a question. Most of the time, several classes can answer to this question.
消息(或通用函数或虚函数)就像一个问题。大多数时候,几个班级都可以回答这个问题。
A corresponding method is a possible answer to the question, that resides in a class.
相应的方法是问题的可能答案,它存在于一个类中。
When sending a message to an instance, the instance looks up for a corresponding method in its class. If found, it calls it (with the instance bound to 'self' or 'this'. Otherwise, it looks for a corresponding method in its mixins, traits, or superclasses, and calls it.
向实例发送消息时,实例会在其类中查找相应的方法。如果找到,则调用它(实例绑定到'self'或'this'。否则,它会在其mixins,traits或superclasses中查找相应的方法,并调用它。
#9
1
If they're old enough to have ever filled out a tax form, show them a 1040EZ and explain that an instance of a class is like a filled-out form: each blank is a member variable of the object, and the form also includes instructions for what to do with the member variables, and those instructions are the member functions of the object. A class itself is like a master copy of the form, from which you can print off an endless number of blank forms to fill out.
如果他们已经足够大,可以填写税表,请向他们展示1040EZ,并解释一个类的实例就像一个填写的表单:每个空白是对象的成员变量,表单还包括如何处理成员变量的说明,这些指令是对象的成员函数。类本身就像是表单的主副本,您可以从中打印出无数个空白表单来填写。
One thing that I would counsel to AVOID in trying to communicate the concepts of OO to new programmers is using only examples where objects (in the OO sense) represent real-world physical objects. This will actually make students more confused when they encounter objects used to represent non-physical objects (such as a color scheme, or most of the behavioral patterns in "Design Patterns") or objects used just as a useful way to store related functions and related data in the same place (think Java's java.lang.Math for an example.)
在尝试将OO的概念传达给新程序员时,我会建议AVOID的一件事是仅使用对象(在OO意义上)代表现实世界的物理对象的示例。这实际上会让学生在遇到用于表示非物理对象的对象(例如颜色方案或“设计模式”中的大多数行为模式)或者仅用作存储相关功能的有用方法的对象时更加困惑。相关数据在同一个地方(以Java的java.lang.Math为例。)
#10
1
Believe it or not, sports!
信不信由你,体育!
I've had success in teaching and mentoring by talking about the way that e.g. a play for a football team is described in terms of how the various positions (Center, Quarterback, Runningback, etc.) interact to accomplish a particular goal. In one version, the positions correspond to classes, and specific persons (Tony Romo, Johnny Unitas, etc.) are instances of the class -- individuals who exhibit the same behaviors as defined by the positions.
我通过谈论如下的方式在教学和辅导方面取得了成功。根据各种位置(中心,四分卫,跑卫等)如何相互作用来完成特定目标,描述了足球队的比赛。在一个版本中,职位对应于班级,特定人员(Tony Romo,Johnny Unitas等)是班级的实例 - 表现出与职位相同的行为的个人。
The second version of this metaphor is to explain that the positions may be interfaces (in the Java sense) rather than classes. An interface really represents a role fulfilled by any object that implements the methods of the interface. And it's perfectly reasonable for an object (via its class, in Java) to implement multiple interfaces, just as it is possible for a talented individual to play more than one position on a sports team.
这个比喻的第二个版本是解释位置可能是接口(在Java意义上)而不是类。接口实际上代表实现接口方法的任何对象所实现的角色。对于一个对象(通过它的类,用Java)来实现多个接口是完全合理的,就像一个有才能的人可以在一个运动团队中扮演多个位置一样。
Finally, the play is like a pattern, in that it describes how a set of roles interact to accomplish some specific goal.
最后,该游戏就像一个模式,因为它描述了一组角色如何相互作用以实现某个特定目标。
#11
1
An object is a black box, which you can't see through. Public methods are buttons on them. Protected methods are buttons hidden on the bottom, private methods are dip switches inside.
一个物体是一个黑盒子,你无法看透。公共方法是它们上的按钮。受保护的方法是隐藏在底部的按钮,私有方法是在内部的dip开关。
Let's see a washer as an object. We don't know how it works. We don't care if it's powered by natural gas, diesel, electricity, or plutonium. However, the mechanism and internal structure will vary greatly depending on the energy source like a combustion engine is needed for some. We don't care as long as if we push a "Wash" button, it washes our clothes.
让我们看一个垫圈作为对象。我们不知道它是如何工作的。我们不关心它是否由天然气,柴油,电力或钚提供动力。然而,机械和内部结构将根据能源而变化很大,就像某些人需要内燃机一样。我们不在乎,只要我们按下“洗涤”按钮,它就会洗掉我们的衣服。
Let's turn the washer not Object-oriented. Expose all the buttons by arranging them on the top. Customers can now turbo-charge the engine by tweaking some dip switches. Make the chassis transparent. Now, you can see your energy-saving washing machine is actually hybrid-powered. There are some monkeys in it. You free them into the wild, and the machine eats up your utility bill like a gas-guzzler.
让我们把洗衣机变成面向对象的。将所有按钮排列在顶部,露出所有按钮。客户现在可以通过调整一些拨码开关对发动机进行涡轮增压。使机箱透明。现在,你可以看到你的节能洗衣机实际上是混合动力的。里面有一些猴子。你将它们释放到野外,机器就像一个耗油的人一样吃掉你的公用事业账单。
#12
0
Object-oriented programming is one technique of raising the level of abstraction by means of which the programmer communicates with the computer: from the level of flipping individual bits on and off, from the level of punching holes in paper cards, from the level of extraordinarily complex sequences of basic instruction codes, from the level of less complicated definitions of reusable templates for blocks of data and reusable blocks of code (structs and procedures), to the level of transcribing the concepts in the programmer's mind into code, so that what goes on inside the computer comes to resemble, for the programmer, what goes on outside the computer in the world of physical objects, intangible assets, and cause-and-effect.
面向对象编程是提高程序员与计算机通信的抽象级别的一种技术:从打开和关闭各个位的级别,从纸卡的打孔级别,从异常级别开始复杂的基本指令代码序列,从用于数据块的可重用模板的不太复杂的定义和可重用的代码块(结构和过程)的级别,到将程序员心中的概念转录为代码的级别,以便在计算机内部,对于程序员来说,在物理对象,无形资产和因果关系的世界中,计算机外部会发生什么。
#13
0
the best book i've ever on object-oriented programming is Betrand's "Object-Oriented Software Construction" - if you really want to get the basics, there is no way around it.
关于面向对象编程的最好的书是Betrand的“面向对象的软件构建” - 如果你真的想要获得基础知识,那么就无法解决它。
#14
0
I explain that procedural program is built around the "verbs" of the system, the things you want the system to do, whereas object-oriented programming is build about the "nouns," the things in the system, and what they are capable of, and that for many people this allows for a more straightforward mapping from the problem domain to software.
我解释说,程序程序是围绕系统的“动词”构建的,是系统要做的事情,而面向对象的程序设计则是关于“名词”,系统中的事物,以及它们的能力。 ,对于许多人来说,这允许从问题域到软件的更直接的映射。
For the example, I use cars -- "Honda Accord" is a class, whereas the vehicle sitting in the parking lot is an object, an instance of a Honda Accord. A Honda Accord is a sedan, which is a car, which is an automobile, which is a motorized vehicle, which is a mode of transportation, etc. I cannot do anything with a car until I have a physical car to work with -- it doesn't help me that the idea of a Honda Accord exists.
例如,我使用汽车 - “本田雅阁”是一类,而坐在停车场的车辆是一个物体,本田雅阁的一个例子。本田雅阁是一辆轿车,这是一辆汽车,是一种汽车,是一种机动车,这是一种交通工具等。在我有一辆实体车与之合作之前我无法做任何事情 - 本田雅阁的概念存在并不能帮助我。
It also helps for discussing interfaces and polymorphism -- the gas pedal means accelerate, regardless what the car does behind the scenes to make that happen. There are "private" parts of the car that I as user do not have access to -- I cannot directly apply an individual brake.
它还有助于讨论接口和多态性 - 加速踏板意味着加速,无论汽车在幕后做什么来实现这一点。我用户无法访问汽车的“私人”部件 - 我无法直接应用单独的制动器。
#15
0
Since the issue is to explain to a new programmer and not to a mother or a wife, I would go right straight to the point. OO is about three main concepts:
既然问题是要向新的程序员而不是母亲或妻子解释,我会直截了当地说明问题。 OO主要涉及三个主要概念:
- Inheritance: a dog is an animal, parent-child, is-a relationship test, etc.
- Encapsulation: public-private (protected), information hiding, internal underlying details are not important to the users of the class, protect users from future changes in the implementation.
- Polymorphism: run-time binding, late binding, method that gets invoked depends on the type of the object and not the reference or pointer to the object.
遗产:狗是动物,亲子,是关系测试等。
封装:公共 - 私有(受保护),信息隐藏,内部底层细节对类的用户并不重要,保护用户免受未来实施的变化。
多态性:运行时绑定,后期绑定,被调用的方法取决于对象的类型,而不是对象的引用或指针。
Also, depending on how much the new programmer has been doing a procedural language, I would need to help him/her unlearn that the functions or procedures are no longer central.
此外,根据新程序员使用程序语言的程度,我需要帮助他/她忘记函数或过程不再是中心。
#16
0
Games are good. There are gameobjects, from this walls, enemies and players inherit. The gameobjects should be renderable have collision-logic etc. The enemies have ai-logic while the player is keyboard controlled.
游戏很好。有游戏对象,从这些墙壁,敌人和玩家继承。游戏对象应该是可渲染的,具有碰撞逻辑等。当玩家受键盘控制时,敌人具有动态逻辑。
Some UI-elements are also good, there are buttons, inputboxes etc that all inherit from some baseobject that has code for managing mouse-events etc.
一些UI元素也很好,有按钮,输入框等都从一些baseobject继承,它们具有管理鼠标事件等的代码。
I don't like the animal-example because i've never seen a "real" program that has ever had to use of animals in that way. It will only make people use inheritance all over the place and you will end up with cubes inheriting from rectangles that inherit from lines (why does so many books insist on using this as example? ).
我不喜欢这个动物的例子,因为我从来没有见过曾经以这种方式使用过动物的“真实”程序。它只会让人们在整个地方使用继承,你最终会得到从行继承的矩形继承的多维数据集(为什么这么多书仍然坚持使用它作为例子?)。
#17
0
OOP is a higher level of abstraction, a programmer can't really come to grasp it unless he has a good understanding of the normal (read: procedural) way of programming, and he must be able to write some programs that do something useful.
OOP是一个更高级别的抽象,程序员无法真正掌握它,除非他非常了解正常(读取:程序)编程方式,并且他必须能够编写一些有用的程序。
For me it took a series of several lectures by one of my university profs, where he discussed many theoretical aspects of programming, he tried to convince us that programming is about manipulating data, and that this data is a representation of the "state(s)" of the program, and some other abstract stuff that I forgot now! But the point is, it's hard to understand OOP without some theoretical abstract discussion first, and this discussion wouldn't make any sense to a person who hadn't had experience writing some real code.
对我来说,我的一位大学教授参加了一系列的讲座,在那里他讨论了编程的许多理论方面,他试图说服我们编程是关于操纵数据,而这个数据是“状态”的表示。 )“该程序,以及我现在忘记的一些其他抽象的东西!但问题是,如果没有一些理论上的抽象讨论,首先很难理解OOP,而这种讨论对于没有经验编写实际代码的人来说没有任何意义。
After the theoretical discussion, you give an example of a moderately complex program, written in procedural style, and slowly convert it, step by step, into object oriented style. After the concrete example, you should go back to the theoretical discussion and just summarize the main points, directly relate the theoretical constructs to the concrete example, e.g you can talk about how the name, age, and salary of an employee represent his state.
在理论讨论之后,您举一个中等复杂程序的例子,用程序风格编写,然后逐步将其逐步转换为面向对象的风格。在具体的例子之后,你应该回到理论上的讨论,只是总结一下要点,直接将理论结构与具体的例子联系起来,例如,你可以谈谈一个雇员的姓名,年龄和工资如何代表他的国家。