
Originally Posted by
koujie
c# program that will show inhertance, encapsulana and polymorphsm
I'll try to give and example to you. To other members/posters correct me if i got something wrong
*Inheritance* - by my own understanding, getting the traits of a parent.
So example:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Student : Person
{
public string School { get; set; }
}
Basically you can do this.
Person person = new Person {;
Name = "dfd" // or you can also retrieve it.
Age = 2
};
// See the Student class which inherits the Person class, got the properties "Name" and "Age" also.
Student student = new Student {
Name = "Ako budoy",
Age = 21,
School = "Smart University"
};
* Encapsulation * - I think this is hiding or not letting other classes modify the value of an object. Research lang ni TS.
Example:
class Person
{
private string _typeOfAnimal;
public string TypeOfAnimal
{
get { return _typeOfAnimal; }
}
public Person()
{
_typeOfAnimal = "Human";
}
// for short hand you can do this: public string TypeOfAnimal { get; private set; }
// Constructor should be like this too: public Person { TypeOfAnimal = "Human"; }
}
This class has TypeOfAnimal property in which you can only change its value inside the class. Other class can only get its value but not change it.
* Polymorphism * a function nga mag usab2x ang buhaton depending on the object nga nagProvide.
E.g.
Animals can move.
Fish moves by swimming.
Birds moves by flying
Humans moves by walking
So moving has is different depending on kinsa ang niMove. so ana pud ang polymorphism.
E.g.
interface IAnimal
{
void Move();
}
class Fish : IAnimal
{
public void Move()
{
WriteLine("Swim");
}
}
class Bird : IAnimal
{
public void Move()
{
WriteLine("Fly");
}
}
class Human : IAnimal
{
public void Move()
{
WriteLine("Walk");
}
}
IAnimal animal = new Human();
animal.Move(); // should display "walk"
animal = new Bird();
animal.Move(); // should display "fly"
animal = new Fish();
animal.Move() = // should display "swim"
So ana..
Hope this helps.