14 Replies - 781 Views - Last Post: 02 October 2013 - 06:50 PM Rate Topic: -----

#1 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Sense of the objects

Posted 01 October 2013 - 08:46 AM

Hi, i am now trying to understand thinking more object instead of currently creating code but more like an object and not duplicating code, so i started to learn abstract classes, interfaces etc. instead of got one or more class and duplicate things. Anyway please check sample code below, i cant understand why we are using this one e.g:
CountClass counter100 = new Count100Class(1);


if we can get the same result as:
Count100Class counter100 = new Count100Class(1);



why we do in this way? I would like to better understand.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            CountClass counter1 = new CountClass(1);
            CountClass counter100 = new Count100Class(1);

            System.Console.WriteLine("Count in base class = {0}", counter1.StepUp());
            System.Console.WriteLine("Count in derived class = {0}", counter100.StepUp());
            Console.ReadLine();
        }
    }

    public class CountClass
    {
        public int count;

        public CountClass(int startValue)  // constructor
        {
            count = startValue;
        }

        public virtual int StepUp()
        {
            return ++count;
        }
    }

    class Count100Class : CountClass
    {
        public Count100Class(int x)
            : base(x)  // constructor 
        {
        }

        public override int StepUp()
        {
            return ((base.count) + 100);
        }
    }


}



Is This A Good Question/Topic? 0
  • +

Replies To: Sense of the objects

#2 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4469
  • View blog
  • Posts: 7,780
  • Joined: 08-June 10

Re: Sense of the objects

Posted 01 October 2013 - 08:58 AM

It's an example explaining how you can do this, not why you would do this. And in your example, I agree, I wouldn't do it that way.

But here's a better example. FtpWebRequest, HttpWebRequest, and FileWebRequest all descend from the abstract WebRequest class. If I had to make a series of requests, I could make an array or list of WebRequest and process them all the same. Even though they do different things, they still extend the same base class, so I can treat them as if they were that base class.

That's the idea. You can treat objects as their common ancestors to make things easier when you have different objects that share a common ancestor.
Was This Post Helpful? 3
  • +
  • -

#3 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 355
  • View blog
  • Posts: 1,521
  • Joined: 08-April 09

Re: Sense of the objects

Posted 01 October 2013 - 09:04 AM

I think what Curtis is explaining is inheritance and polymorphism, right?
Was This Post Helpful? 0
  • +
  • -

#4 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Re: Sense of the objects

Posted 01 October 2013 - 09:11 AM

my example was from MSDNA: http://msdn.microsof...7(v=vs.90).aspx :)/> . But i still cant get it, the same situation i seen in other examples e.g when we had classes such ass Employee, Manager, ChiefofManagers for instance, and in code some of people were using such thing like this:
Employee employee = new Employee();
Employee employee = new Manager();
Manager manager = new ChiefOfManagers();



Also in this example also from MSDNA:
public abstract class Employee 
{ 
    protected string name;

    public Employee(string name)  // constructor
    { 
        this.name = name;
    }

    public abstract void Show();  // abstract show method
}

public class Manager: Employee
{ 
    public Manager(string name) : base(name) {}  // constructor 

    public override void Show()  //override the abstract show method
    {
        System.Console.WriteLine("Name : " + name);
    }
}

class TestEmployeeAndManager
{ 
    static void Main()
    { 
        // Create an instance of Manager and assign it to a Manager reference:
        Manager m1 = new Manager("H. Ackerman");
        m1.Show();

        // Create an instance of Manager and assign it to an Employee reference:
        Employee ee1 = new Manager("M. Knott");
        ee1.Show();  //call the show method of the Manager class
    } 
}




this one:
Employee ee1 = new Manager("M. Knott");



what i cant understand why in some cases it is used for? Maybe some other example which i can get it would be appreciate from your side.

This post has been edited by nighttrain: 01 October 2013 - 09:14 AM

Was This Post Helpful? 0
  • +
  • -

#5 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Sense of the objects

Posted 01 October 2013 - 09:12 AM

Since the example is short and contrived, I can see why you have an issue understanding it. Let's try something else short and contrived :)/>

Let us say that you need to create an application for a zoo. Since you are an OO programmer, you decide to have a base 'Animal' class. In this class you'll have a 'Feed' method, as all the animals have to eat!

public abstract class Animal {
    public abstract void Feed();
}


So now you create some animals from this class:
public class Monkey : Animal {
    public override void Feed() { Console.WriteLine("Give me a banana."); }
}

public class Bat : Animal {
    public override void Feed() { Console.WriteLine("I like bugs!"); }
}

public class Vampire : Bat {
    public override void Feed() { Console.WriteLine("I want your blood!"); }
}


Now you'd normally have to maintain three lists to hold all the animals:
List<Monkey> monkeys = new List<Monkey>();
monkeys.Add(new Monkey);

List<Bat> bats = new List<Bat>();
bats.Add(new Bat());

List<Vampire> vampires = new List<Vampire>();
vampires.Add(new Vampire());


And if we wanted to feed them all
public void FeedTheAnimals() {
    foreach (Monkey m in monkeys) m.Feed();
    foreach (Bat b in bats) b.Feed();
    foreach (Vampire v in vampires) v.Feed();
}


Now what happens if you get an elephant? You need to create an elephant class, a list to hold the elephants, and modify the FeedTheAnimals method to include elephants! But, because everything inherits from the abstract class Animal, we can make this easy! So we change our list(s) of the various animals to
List<Animal> animals = new List<Animal>();

animals.Add(new Monkey());
animals.Add(new Bat());
animals.Add(new Vampire());
And our FeedTheAnimals becomes
public void FeedTheAnimals() {
    foreach (Animal a in animals) a.Feed();
}

Now if you add an elephant, you don't need another list, the method doesn't change, etc. This is one of the things that inheritance does for us.

So, all the way back to your original problem, they did that because you might want to create a different class that, for example, counted by 50s but you'd only have to change the assignment, not any of the other code.

P.S. I didn't deal with scope in my examples so you might have issues getting it to work if you don't understand scope.

This post has been edited by Momerath: 01 October 2013 - 09:19 AM

Was This Post Helpful? 4
  • +
  • -

#6 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Re: Sense of the objects

Posted 01 October 2013 - 09:24 AM

but in this case you also need to implement class Elephant
Was This Post Helpful? 0
  • +
  • -

#7 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Sense of the objects

Posted 01 October 2013 - 09:26 AM

Yes you would, but I leave that as an exercise for the reader :)
Was This Post Helpful? 0
  • +
  • -

#8 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Re: Sense of the objects

Posted 01 October 2013 - 09:27 AM

so after i put it inside Animal class:
public void FeedTheAnimals() {  

     foreach (Animal a in animals) a.Feed();  

 } 



it will execute all Feed methos from each iclasses which inheritance from Animal right? No it has no sense i cannot execute it lets say in Main because i cant make an instance of abstract class and invoke the FeedTheAnimals from there .

This post has been edited by nighttrain: 01 October 2013 - 09:30 AM

Was This Post Helpful? 0
  • +
  • -

#9 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 355
  • View blog
  • Posts: 1,521
  • Joined: 08-April 09

Re: Sense of the objects

Posted 01 October 2013 - 09:49 AM

Try and see what happens, this is a good point for you to learn debugging so you can see the code flow, to see what happens inside Debugging, this is the most useful thing a programmer can learn.
Was This Post Helpful? 0
  • +
  • -

#10 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Re: Sense of the objects

Posted 01 October 2013 - 10:18 AM

ok, i compiled that code:
Spoiler


i see how the code works and its fine i know exactly.
1. In case of add new class let's say Elephant correct me if i am wrong: first i would need to add a class elephant and add additional line inside my exisiting list right?: animals.Add(new Elephant());

2. Anyhow i still cant get the point from the first post or in this code:

Spoiler


Note that i know in this case this one:
Employee ee1 = new Manager("M. Knott");


give me the same result as i would write:
Manageree1 = new Manager("M. Knott");



I just can;t understand why people using it in THIS WAY sometimes when see the code.

This post has been edited by nighttrain: 01 October 2013 - 10:21 AM

Was This Post Helpful? 0
  • +
  • -

#11 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 355
  • View blog
  • Posts: 1,521
  • Joined: 08-April 09

Re: Sense of the objects

Posted 01 October 2013 - 10:36 AM

If you want to add new animal, create new Elephant class that extends Animal class and make override method for Feed
public class Elephant : Animal
{
  public override void Feed()
 {
   Console.Writeline("Give me elephant food");
 }
}

then you can do
animals.Add(new Elephant());
in your main with others Animals

2. You need to understand that every manager is employee but not every employee is manager. Even in inheritance you need to performs things that are bit different than the others, that is where the override come in, you can keep the hierarchy with inheritance but override certain elements that are only applicable to the specific class, in this case Manager. Managers can have different way their paycheck is calculated but since they are employees like the other they want to keep all the benefits of the Employee class but keep certain perks that only apply to them.

This post has been edited by Michael26: 01 October 2013 - 10:48 AM

Was This Post Helpful? 0
  • +
  • -

#12 nighttrain  Icon User is online

  • D.I.C Regular

Reputation: 5
  • Posts: 316
  • Joined: 22-September 10

Re: Sense of the objects

Posted 01 October 2013 - 11:14 AM

ok so am i right telling that: this is exactly objective thinking that Manager is also Employee that's why e.g:
Employee employee = new Manager();



and not:

Manager employee = new Manager();



because both would work the same that objective thinking and good hierarchie with like u said oveeriding for specific should in this case be in objective as:

Employee employee = new Manager();


Was This Post Helpful? 0
  • +
  • -

#13 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: Sense of the objects

Posted 01 October 2013 - 12:04 PM

Yes, but I think Curtis was spot on. Examples like this are not usually very good at conveying the "why" you would choose to do something, they just demonstrate "how" you would do it. In such a simple example, it doesn't matter which way you do it.

However, you can nevertheless glean a lot of insight into many fundamental OOP principles from this simple code, as you'll hopefully see from the rest of this post.

Employee employee = new Manager();


That code demonstrates one aspect of the Program to an interface, not an implementation principle. One of the basic ideas behind this is that you can write a bunch of code that uses the employee variable, and not care about whether employee is actually a manager, a supervisor, a chief of managers etc. That greatly simplifies the job of implementing the code, and will likely result in better, more general, flexible code.

Further though, because you are programming only to the (possibly restricted) Employee 'interface', you can change your employee declaration to this Employee employee = new Supervisor();, for example, and you can be confident that all your code will continue to work (assuming the Liskov Substitution principle has been adhered to). That can be an extremely valuable tool in the more complex applications we get in the real world.

If you only need the methods of the Employee class to do your work, why make your code more brittle by programming to a more specific concrete type? Being restrictive in the interface you provide to client code is another good guideline that this sort of code can help achieve (see the Interface Segregation Principle).

The principle of programming to an interface is often more powerful (and makes more real world sense) when combined with Inversion of Control (possibly via Dependency Injection).

Quote

but in this case you also need to implement class Elephant


Yes, and, just to clarify, that is generally a good thing. If you find yourself extending your application's functionality solely by adding new classes, you are probably designing your application quite well. If all you are doing is adding new classes, you can't break existing classes, and all you have to worry about is testing and verifying the new class works, right? :) (See the Open/Closed Principle).

This post has been edited by CodingSup3rnatur@l-360: 01 October 2013 - 12:47 PM
Reason for edit:: Closed open url tag + spelling

Was This Post Helpful? 4
  • +
  • -

#14 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Sense of the objects

Posted 01 October 2013 - 12:30 PM

And all the stuff mentioned by CodingSup3rnatur@l-360 leads to SOLID.

Interestingly enough (well, to me at least), I recently read a job posting where they asked for x years experience in y, etc. or that you explain what SOLID stands for and can give some examples.

This post has been edited by Momerath: 01 October 2013 - 12:31 PM
Reason for edit:: bad username, curse you cut/paste

Was This Post Helpful? 1
  • +
  • -

#15 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Sense of the objects

Posted 02 October 2013 - 06:50 PM

I'm a little late to the party but... There is a tutorial on objects linked in my signature block.

Also this tutorial on building a Cash Register is very OOP oriented and demonstrates inheriting one kind of keypad from a more generic parent. Whether its a keypad or a mammal inheritance works the same.
http://www.dreaminco...ister-part-one/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1