How to handle variables correcly in C# composition? -


what correct implementation of composition here? have class cat, contains _gallonsofmilkeaten variable, because cats drink milk. have animal class age, because animals have age. now, need use age variable in both cat , dog classes.

should this:

class animal {     public float age = 35; }  class cat {     private float _gallonsofmilkeaten;     private animal _animal = new animal();      public void meow()     {          debug.log("this dog ate "+_gallonsofmilkeaten+" gallons of milk , " + _animal.age+" years old." )}     } }   class dog {     private float _bonesburried;     private animal _animal = new animal();      public void woof()     {        //...     } } 

or this, each of them has own definiton of variable?:

class animal {  }  class cat {     private float _gallonsofmilkeaten;     private animal _animal = new animal();     private float _age = 35;      public void meow()     {          debug.log("this dog ate "+_gallonsofmilkeaten+" gallons of milk , " + _age+" years old." )}     } }   class dog {     private float _bonesburried;     private animal _animal = new animal();     private float _age = 35;      public void woof()     {        //...     } } 

first, code makes sense in case have reason use composition instead of inheritance. inheritance should default choice since dogs , cats are animals not have animals.

you should keep age in animal class, if don't what's point of having class? however, should not define public field, public read property preferred:

class animal {     private float _age = 35;     public float age {        {          return this._age;        }     } }     class cat {     private float _gallonsofmilkeaten;     private animal _animal = new animal();      public void meow() {          debug.log("this dog ate "+_gallonsofmilkeaten+" gallons of milk , " + _animal.age +" years old." )}     } }  class dog {     private float _bonesburried;     private animal _animal = new animal();      public void woof() {        //...     } } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -