问题描述
我的亲戚正在学习编程,并且很难理解课程.他很难理解,例如您需要实例化它,方法无法访问其他方法中的变量,并且如果您在类的一个实例中更改了变量,则在其他实例中也不会更改.
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.
您如何大致解释类和OO?
How do you explain classes and OO in general?
推荐答案
认真使用Animals,效果很好.这就是几年前为我钉上这个概念的东西.刚发现此C#代码.看起来不错
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
// 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());
}
}
}
一旦他搞定了,就挑战他来定义Bird(飞行),然后定义Penguin(飞行!?)
And once he's got this nailed, you challenge him to define Bird (fly), and then Penguin (fly!?)
这篇关于您如何向新程序员解释面向对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!