Search Results

Search found 1494 results on 60 pages for 'prototypal inheritance'.

Page 1/60 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Explanation of the definition of interface inheritance as described in GoF book

    - by Geek
    I am reading the first chapter of the Gof book. Section 1.6 discusses about class vs interface inheritance: Class versus Interface Inheritance It's important to understand the difference between an object's class and its type. An object's class defines how the object is implemented.The class defines the object's internal state and the implementation of its operations.In contrast,an object's type only refers to its interface--the set of requests on which it can respond. An object can have many types, and objects of different classes can have the same type. Of course, there's a close relationship between class and type. Because a class defines the operations an object can perform, it also defines the object's type . When we say that an object is an instance of a class, we imply that the object supports the interface defined by the class. Languages like c++ and Eiffel use classes to specify both an object's type and its implementation. Smalltalk programs do not declare the types of variables; consequently,the compiler does not check that the types of objects assigned to a variable are subtypes of the variable's type. Sending a message requires checking that the class of the receiver implements the message, but it doesn't require checking that the receiver is an instance of a particular class. It's also important to understand the difference between class inheritance and interface inheritance (or subtyping). Class inheritance defines an object's implementation in terms of another object's implementation. In short, it's a mechanism for code and representation sharing. In contrast,interface inheritance(or subtyping) describes when an object can be used in place of another. I am familiar with the Java and JavaScript programming language and not really familiar with either C++ or Smalltalk or Eiffel as mentioned here. So I am trying to map the concepts discussed here to Java's way of doing classes, inheritance and interfaces. This is how I think of of these concepts in Java: In Java a class is always a blueprint for the objects it produces and what interface(as in "set of all possible requests that the object can respond to") an object of that class possess is defined during compilation stage only because the class of the object would have implemented those interfaces. The requests that an object of that class can respond to is the set of all the methods that are in the class(including those implemented for the interfaces that this class implements). My specific questions are: Am I right in saying that Java's way is more similar to C++ as described in the third paragraph. I do not understand what is meant by interface inheritance in the last paragraph. In Java interface inheritance is one interface extending from another interface. But I think the word interface has some other overloaded meaning here. Can some one provide an example in Java of what is meant by interface inheritance here so that I understand it better?

    Read the article

  • When virtual inheritance IS a good design?

    - by 7vies
    EDIT3: Please be sure to clearly understand what I am asking before answering (there are EDIT2 and lots of comments around). There are (or were) many answers which clearly show misunderstanding of the question (I know that's also my fault, sorry for that) Hi, I've looked over the questions on virtual inheritance (class B: public virtual A {...}) in C++, but did not find an answer to my question. I know that there are some issues with virtual inheritance, but what I'd like to know is in which cases virtual inheritance would be considered a good design. I saw people mentioning interfaces like IUnknown or ISerializable, and also that iostream design is based on virtual inheritance. Would those be good examples of a good use of virtual inheritance, is that just because there is no better alternative, or because virtual inheritance is the proper design in this case? Thanks. EDIT: To clarify, I'm asking about real-life examples, please don't give abstract ones. I know what virtual inheritance is and which inheritance pattern requires it, what I want to know is when it is the good way to do things and not just a consequence of complex inheritance. EDIT2: In other words, I want to know when the diamond hierarchy (which is the reason for virtual inheritance) is a good design

    Read the article

  • Alternative to "inheritance versus composition?" [closed]

    - by Frank
    Possible Duplicate: Where does this concept of “favor composition over inheritance” come from? I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go. I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes. For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?

    Read the article

  • Inheritance vs composition in this example

    - by Gerenuk
    I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments. In particular my example was Inheritance: class Do: def do(self): self.doA() self.doB() def doA(self): pass def doB(self): pass class MyDo(Do): def doA(self): print("A") def doB(self): print("B") x=MyDo() vs Composition: class Do: def __init__(self, a, b): self.a=a self.b=b def do(self): self.a.do() self.b.do() x=Do(DoA(), DoB()) (Note for composition I'm missing code so it's not actually shorter) Can you name particular advantages of one or the other? I'm think of: composition is useful if you plan to reuse DoA() in another context inheritance seems easier; no additional references/variables/initialization method doA can access internal variable (be it a good or bad thing :) ) inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton ... Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is prefered, but I'd like to understand that by example. Of course I can always start with one and refactor later to the other.

    Read the article

  • Looking for a real-world example illustrating that composition can be superior to inheritance

    - by Job
    I watched a bunch of lectures on Clojure and functional programming by Rich Hickey as well as some of the SICP lectures, and I am sold on many concepts of functional programming. I incorporated some of them into my C# code at a previous job, and luckily it was easy to write C# code in a more functional style. At my new job we use Python and multiple inheritance is all the rage. My co-workers are very smart but they have to produce code fast given the nature of the company. I am learning both the tools and the codebase, but the architecture itself slows me down as well. I have not written the existing class hierarchy (neither would I be able to remember everything about it), and so, when I started adding a fairly small feature, I realized that I had to read a lot of code in the process. At the surface the code is neatly organized and split into small functions/methods and not copy-paste-repetitive, but the flip side of being not repetitive is that there is some magic functionality hidden somewhere in the hierarchy chain that magically glues things together and does work on my behalf, but it is very hard to find and follow. I had to fire up a profiler and run it through several examples and plot the execution graph as well as step through a debugger a few times, search the code for some substring and just read pages at the time. I am pretty sure that once I am done, my resulting code will be short and neatly organized, and yet not very readable. What I write feels declarative, as if I was writing an XML file that drives some other magic engine, except that there is no clear documentation on what the XML should look like and what the engine does except for the existing examples that I can read as well as the source code for the 'engine'. There has got to be a better way. IMO using composition over inheritance can help quite a bit. That way the computation will be linear rather than jumping all over the hierarchy tree. Whenever the functionality does not quite fit into an inheritance model, it will need to be mangled to fit in, or the entire inheritance hierarchy will need to be refactored/rebalanced, sort of like an unbalanced binary tree needs reshuffling from time to time in order to improve the average seek time. As I mentioned before, my co-workers are very smart; they just have been doing things a certain way and probably have an ability to hold a lot of unrelated crap in their head at once. I want to convince them to give composition and functional as opposed to OOP approach a try. To do that, I need to find some very good material. I do not think that a SCIP lecture or one by Rich Hickey will do - I am afraid it will be flagged down as too academic. Then, simple examples of Dog and Frog and AddressBook classes do not really connivence one way or the other - they show how inheritance can be converted to composition but not why it is truly and objectively better. What I am looking for is some real-world example of code that has been written with a lot of inheritance, then hit a wall and re-written in a different style that uses composition. Perhaps there is a blog or a chapter. I am looking for something that can summarize and illustrate the sort of pain that I am going through. I already have been throwing the phrase "composition over inheritance" around, but it was not received as enthusiastically as I had hoped. I do not want to be perceived as a new guy who likes to complain and bash existing code while looking for a perfect approach while not contributing fast enough. At the same time, my gut is convinced that inheritance is often the instrument of evil and I want to show a better way in a near future. Have you stumbled upon any great resources that can help me?

    Read the article

  • Code Smell: Inheritance Abuse

    - by dsimcha
    It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful. Delegation can often (though not always) be verbose and brittle. The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle. What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?

    Read the article

  • Code Smell: Inheritance Abuse

    - by dsimcha
    It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful. Delegation can often (though not always) be verbose and brittle. The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle. What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?

    Read the article

  • Alternative to "inheritance v composition??"

    - by Frank
    I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go. I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes. For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?

    Read the article

  • is multiple inheritance a compiler writers problem? - c++

    - by Dr Deo
    i have been reading about multiple inheritance http://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance http://en.wikipedia.org/wiki/Diamond_problem http://en.wikipedia.org/wiki/Virtual_inheritance http://en.wikipedia.org/wiki/Multiple_inheritance But since the code does not compile until the ambiguity is resolved, doesn't this make multiple inheritance a problem for compiler writers only? - how does this problem affect me in case i don't want to ever code a compiler

    Read the article

  • Confusion about inheritance

    - by Samuel Adam
    I know I might get downvoted for this, but I'm really curious. I was taught that inheritance is a very powerful polymorphism tool, but I can't seem to use it well in real cases. So far, I can only use inheritance when the base class is an abstract class. Examples : If we're talking about Product and Inventory, I quickly assumed that a Product is an Inventory because a Product must be inventorized as well. But a problem occured when user wanted to sell their Inventory item. It just doesn't seem to be right to change an Inventory object to it's subtype (Product), it's almost like trying to convert a parent to it's child. Another case is Customer and Member. It is logical (at least for me) to think that a Member is a Customer with some more privileges. Same problem occurred when user wanted to upgrade an existing Customer to become a Member. A very trivial case is the Employee case. Where Manager, Clerk, etc can be derived from Employee. Still, the same upgrading issue. I tried to use composition instead for some cases, but I really wanted to know if I'm missing something for inheritance solution here. My composition solution for those cases : Create a reference of Inventory inside a Product. Here I'm making an assumption about that Product and Inventory is talking in a different context. While Product is in the context of sales (price, volume, discount, etc), Inventory is in the context of physical management (stock, movement, etc). Make a reference of Membership instead inside Customer class instead of previous inheritance solution. Therefor upgrading a Customer is only about instantiating the Customer's Membership property. This example is keep being taught in basic programming classes, but I think it's more proper to have those Manager, Clerk, etc derived from an abstract Role class and make it a property in Employee. I found it difficult to find an example of a concrete class deriving from another concrete class. Is there any inheritance solution in which I can solve those cases? Being new in this OOP thing, I really really need a guidance. Thanks!

    Read the article

  • Javascript functional inheritance with prototypes

    - by cdmckay
    In Douglas Crockford's JavaScript: The Good Parts he recommends that we use functional inheritance. Here's an example: var mammal = function(spec, my) { var that = {}; my = my || {}; // Protected my.clearThroat = function() { return "Ahem"; }; that.getName = function() { return spec.name; }; that.says = function() { return my.clearThroat() + ' ' + spec.saying || ''; }; return that; } var cat = function(spec, my) { var that = {}; my = my || {}; spec.saying = spec.saying || 'meow'; that = mammal(spec, my); that.purr = function() { return my.clearThroat() + " purr"; }; that.getName = function() { return that.says() + ' ' + spec.name + ' ' + that.says(); }; return that; }; var kitty = cat({name: "Fluffy"}); The main issue I have with this is that every time I make a mammal or cat the JavaScript interpreter has to re-compile all the functions in it. That is, you don't get to share the code between instances. My question is: how do I make this code more efficient? For example, if I was making thousands of cat objects, what is the best way to modify this pattern to take advantage of the prototype object?

    Read the article

  • improve javascript prototypal inheritance

    - by Julio
    I'm using a classical javascript prototypal inheritance, like this: function Foo() {} Naknek.prototype = { //Do something }; var Foo = window.Foo = new Foo(); I want to know how I can improve this and why I can't use this model: var Foo = window.Foo = new function() { }; Foo.prototype = { //Do something }; Why this code doesn't work? In my head this is more logical than the classical prototypal inheritance.

    Read the article

  • Capitalizing on JavaScript's prototypal inheritance

    - by keithjgrant
    JavaScript has a class-free object system in which objects inherit properties directly from other objects. This is really powerful, but it is unfamiliar to classically trained programmers. If you attempt to apply classical design patterns directly to JavaScript, you will be frustrated. But if you learn to work with JavaScript's prototypal nature, your efforts will be rewarded. ... It is Lisp in C's clothing. -Douglas Crockford What does this mean for a game developer working with canvas and HTML5? I've been looking over this question on useful design patterns in gaming, but prototypal inheritance is very different than classical inheritance, and there are surely differences in the best way to apply some of these common patterns. For example, classical inheritance allows us to create a moveableEntity class, and extend that with any classes that move in our game world (player, monster, bullet, etc.). Sure, you can strongarm JavaScript to work that way, but in doing so, you are kind of fighting against its nature. Is there a better approach to this sort of problem when we have prototypal inheritance at our fingertips?

    Read the article

  • Dynamic Class Inheritance For PHP

    - by VirtuosiMedia
    I have a situation where I think I might need dynamic class inheritance in PHP 5.3, but the idea doesn't sit well and I'm looking for a different design pattern to solve my problem if it's possible. Use Case I have a set of DB abstraction layer classes that dynamically compiles SQL queries, with one DAL class for each DB type (MySQL, MsSQL, Oracle, etc.). Each table in the database has its own class that extends the appropriate DAL class. The idea is that you interact with the table classes, but never directly use the DAL class. If you want to support a different DB type for your app, you don't need to rewrite any queries or even any code, you simply change a setting that swaps one DAL class out for another...and that's it. To give you a better idea of how this is used, you can take a look at the DAL class, the table classes, and how they are used on this StackExchange Code Review page. To really understand what I'm trying to do, please take a look at my implementation first before suggesting a solution. Issues The strategy that I had used previously was to have all of the DAL classes share the same class name. This eliminated autoloading, so I had to manually load the appropriate DAL class in a switch statement. However, this approach presents some problems for testing and documentation purposes, so I'd like to find a different way to solve the problem of loading the correct DAL class more elegantly. Update to clarify the issue The problem basically boils down to inconsistencies in the class name (pre-PHP 5.3) or class namespace (PHP 5.3) and its location in the directory structure. At this point, all of my DAL classes have the same name, DBObject, but reside in different folders, MySQL, Oracle, etc. My table classes all extend DBObject, but which DBObject they extend varies depending on which one has been loaded. Basically, I'm trying to have my cake and eat it too. The table classes act as a stable API and extend a dynamic backend, the DAL (DBObject) classes. It works great, but I outsmarted myself and because of the inconsistencies with the class names and their locations, I can't autoload the DBObject, which makes running unit tests and generating API docs impossible for the DBObject classes because the tests and docs rely on auto-loading. Just loading the appropriate DBObject into memory using a factory method won't work because there will be times when I need to load multiple DBObjects for testing. Because the classes currently share a name, this causes a class is already defined error. I can make exceptions for the DBObjects in my test code, obviously, but I'm looking for something a little less hacky as there may future instances where something similar would need to be done. Solutions? Worst case scenario, I can continue my current strategy, but I don't like it very much, especially as I'll soon be converting my code to PHP 5.3. I suspect that I can use some sort of dynamic inheritance via either namespaces (preferred) or a dynamic class extension, but I haven't been able to find good examples of this implemented in the wild. In your answers, please suggest either an alternate pattern that would work for this use case or an example of dynamic inheritance done right. Please assume PHP 5.3 with namespaced code. Any code examples are greatly encouraged. The preferred constraints for the solution are: DAL class can be autoloaded. DAL classes don't share the same exact same namespace, but share the same class name. As an example, I would prefer to use classes named DbObject that use namespaces like Vm\Db\MySql and Vm\Db\Oracle. Table classes don't have to be rewritten with a change in DB type. The appropriate DB type is determined via a single setting only. That setting is the only thing that should need to change to interchange DB types. Ideally, the setting check should occur only once per page load, but I'm flexible on that.

    Read the article

  • Should I use concrete Inheritance or not?

    - by Mez
    I have a project using Propel where I have three objects (potentially more in the future) Occasion Event extends Occasion Gig extends Occasion Occasion is an item that has the shared things, that will always be needed (Venue, start, end etc) With this - I want to be able to add in extra functionality, say for example, adding "Band" objects to the Gig object, or "Flyers" to an "Event" object. For this, I plan to create objects for these. However, without concrete inheritance, I have to have the foreign key point to the Occasion object - giving the (propel generated) functions for all of these extra bits to anything inherited from Occasion. I could, in theory do this without a foreign constraint, and add in functions to use the Peer or Query classes to get things related to the "Gig" or similar. Whereas with concrete inheritance, I would only have these functions in the things where they are. I think the decision here is whether I should Duck Type the objects (after all they are occasions) or whether I should just use the "Occasion" object as a "template" (only being used to search for things, like, all occasions at a venue) Thoughts? Comments?

    Read the article

  • Example of persisting an inheritance relationship using ORM

    - by Schemer
    I have some experience with OOP and RDBs, but very little exposure to web programming. I am trying to understand what non-trivial types of problems are solved by ORM. Of course, I am familiar with the need for data persistence, but I have never encountered a need for persisting relationships between objects, a situation which is indicated in many online articles about ORM. I am not asking about the process of persisting a POJO to a database and restoring it later. Nor am I asking about why ORM frameworks are useful -- or a pain in the butt -- for doing so. I am particularly interested in how the need arises to persist and restore relationships between objects. In various documentation, I have seen many examples of persisting POJOs to a database, but the examples have all been for only very simple objects that are essentially nothing more than records anyway: a constructor, some private fields, and getter/setter methods. The motivation for persisting such an "object-record" seems obvious and trivial. This example: Hibernate ORM Tutorial offers such an example, but goes on to discuss mismatch issues of granularity, inheritance, identity, associations, and navigation that are not motivated by the example. If someone could offer a toy example of an instance where, say, the need arises to persist an inheritance relationship, I would be grateful. This might be blindingly obvious for anyone who has already encountered this situation but I have not and a great deal of searching and reading have not turned up any examples.

    Read the article

  • Virtual Inheritance Confusion

    - by alan
    I'm reading about inheritance and I have a major issue that I haven't been able to solve for hours: Given a class Bar is a class with virtual functions, class Bar { virtual void Cook(); } What is the different between: class Foo : public Bar { virtual void Cook(); } and class Foo : public virtual Bar { virtual void Cook(); } ? Hours of Googling and reading came up with lots of information about its uses, but none actually tell me what the difference between the two are, and just confuse me more. Thanks!

    Read the article

  • Single Table Inheritance (Database Inheritance design options) pros and cons and in which case it us

    - by Yosef
    Hi, I study about today about 2 database design inheritance approaches: 1. Single Table Inheritance 2. Class Table Inheritance In my student opinion Single Table Inheritance make database more smaller vs other approaches because she use only 1 table. But i read that the more favorite approach is Class Table Inheritance according Bill Karwin. My Question is: Single Table Inheritance pros and cons and in which case it used? thanks, Yosef

    Read the article

  • Cant' cast a class with multiple inheritance

    - by Jay S.
    I am trying to refactor some code while leaving existing functionality in tact. I'm having trouble casting a pointer to an object into a base interface and then getting the derived class out later. The program uses a factory object to create instances of these objects in certain cases. Here are some examples of the classes I'm working with. // This is the one I'm working with now that is causing all the trouble. // Some, but not all methods in NewAbstract and OldAbstract overlap, so I // used virtual inheritance. class MyObject : virtual public NewAbstract, virtual public OldAbstract { ... } // This is what it looked like before class MyObject : public OldAbstract { ... } // This is an example of most other classes that use the base interface class NormalObject : public ISerializable // The two abstract classes. They inherit from the same object. class NewAbstract : public ISerializable { ... } class OldAbstract : public ISerializable { ... } // A factory object used to create instances of ISerializable objects. template<class T> class Factory { public: ... virtual ISerializable* createObject() const { return static_cast<ISerializable*>(new T()); // current factory code } ... } This question has good information on what the different types of casting do, but it's not helping me figure out this situation. Using static_cast and regular casting give me error C2594: 'static_cast': ambiguous conversions from 'MyObject *' to 'ISerializable *'. Using dynamic_cast causes createObject() to return NULL. The NormalObject style classes and the old version of MyObject work with the existing static_cast in the factory. Is there a way to make this cast work? It seems like it should be possible.

    Read the article

  • C++ Multiple inheritance with interfaces?

    - by umanga
    Greetings all, I come from Java background and I am having difficulty with multiple inheritance. I have an interface called IView which has init() method.I want to derive a new class called PlaneViewer implementing above interface and extend another class. (QWidget). My implementation is as: IViwer.h (only Header file , no CPP file) : #ifndef IVIEWER_H_ #define IVIEWER_H_ class IViewer { public: //IViewer(); ///virtual //~IViewer(); virtual void init()=0; }; #endif /* IVIEWER_H_ */ My derived class. PlaneViewer.h #ifndef PLANEVIEWER_H #define PLANEVIEWER_H #include <QtGui/QWidget> #include "ui_planeviewer.h" #include "IViewer.h" class PlaneViewer : public QWidget , public IViewer { Q_OBJECT public: PlaneViewer(QWidget *parent = 0); ~PlaneViewer(); void init(); //do I have to define here also ? private: Ui::PlaneViewerClass ui; }; #endif // PLANEVIEWER_H PlaneViewer.cpp #include "planeviewer.h" PlaneViewer::PlaneViewer(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } PlaneViewer::~PlaneViewer() { } void PlaneViewer::init(){ } My questions are: Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView? 2.I cannot complie above code ,give error : PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status Do I have to have implementation for IView in CPP file?

    Read the article

  • [C++] Multiple inheritance from template class

    - by Tom P.
    Hello, I'm having issues with multiple inheritance from different instantiations of the same template class. Specifically, I'm trying to do this: template <class T> class Base { public: Base() : obj(NULL) { } virtual ~Base() { if( obj != NULL ) delete obj; } template <class T> T* createBase() { obj = new T(); return obj; } protected: T* obj; }; class Something { // ... }; class SomethingElse { // ... }; class Derived : public Base<Something>, public Base<SomethingElse> { }; int main() { Derived* d = new Derived(); Something* smth1 = d->createBase<Something>(); SomethingElse* smth2 = d->createBase<SomethingElse>(); delete d; return 0; } When I try to compile the above code, I get the following errors: 1>[...](41) : error C2440: '=' : cannot convert from 'SomethingElse *' to 'Something *' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1> [...](71) : see reference to function template instantiation 'T *Base<Something>::createBase<SomethingElse>(void)' being compiled 1> with 1> [ 1> T=SomethingElse 1> ] 1>[...](43) : error C2440: 'return' : cannot convert from 'Something *' to 'SomethingElse *' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast The issue seems to be ambiguity due to member obj being inherited from both Base< Something and Base< SomethingElse , and I can work around it by disambiguating my calls to createBase: Something* smth1 = d->Base<Something>::createBase<Something>(); SomethingElse* smth2 = d->Base<SomethingElse>::createBase<SomethingElse>(); However, this solution is dreadfully impractical, syntactically speaking, and I'd prefer something more elegant. Moreover, I'm puzzled by the first error message. It seems to imply that there is an instantiation createBase< SomethingElse in Base< Something , but how is that even possible? Any information or advice regarding this issue would be much appreciated.

    Read the article

  • Object inheritance and method parameters/return types - Please check my logic

    - by user2368481
    I'm preparing for a test and doing practice questions, this one in particular I am unsure I did correctly: We are given a very simple UML diagram to demonstrate inheritance: I hope this is clear, it shows that W inherits from V and so on: |-----Y V <|----- W<|-----| |-----X<|----Z and this code: public X method1(){....} method2(new Y()); method2(method1()); method2(method3()); The questions and my answers: Q: What types of objects could method1 actually return? A: X and Z, since the method definition includes X as the return type and since Z is a kind of X is would be OK to return either. Q: What could the parameter type of method2 be? A: Since method2 in the code accepts Y, X and Z (as the return from method1), the parameter type must be either V or W, as Y,X and Z inherit from both of these. Q: What could return type of method3 be? A: Return type of method3 must be V or W as this would be consistent with answer 2.

    Read the article

  • How to use Private Inheritence aka C++ in C# and Why not it is present in C#

    - by Vijay
    I know that private inheritance is supported in C++ and only public inheritance is supported in C#. I also came across an article which says that private inheritance usually defines a HAS-A relationship and kind of an aggregation relationship between the classes. EDIT: C++ code for private inheritance: The "Car has-a Engine" relationship can also be expressed using private inheritance: class Car : private Engine { // Car has-a Engine public: Car() : Engine(8) { } // Initializes this Car with 8 cylinders using Engine::start; // Start this Car by starting its Engine }; Now, Is there a way to create a HAS-A relationship between C# classes which is one of the thing that I would like to know - HOW? Another curious question is why doesn't C# support the private (and also protected) inheritance ? - Is not supporting multiple implementation inheritance a valid reason or any other? Is private (and protected) inheritance planned for future versions of C#? Will supporting the private (and protected) inheritance in C# make it a better and widely used language?

    Read the article

  • Inheritance versus Composition in a business application

    - by ProfK
    I have a training management and tracking system, with a high level structure as follows: We have a Role1, e.g. Manager, Shift-boss, miner, etc. and a Candidate, training for that Role. The role has a list of courses and their subjects the candidate needs to complete to qualify for the role. Candidate has a TrainingHistory attribute, containing the courses and subjects they have completed, their results, and the date completed. Now I see it as a TrainingHistoryCourse is-a Course, extended to add DateCompleted etc. but something is nagging at me to rather use something like a TrainingHistoryRecord that has-a Course. How can I further analyse this to determine which pattern to use? Then, a Role has a list of RoleTask definitions that the Candidate must be observed practising, and a Candidate has a history of RoleTaskObservation objects recording their performance at these tasks. This is very similar to the course/subject requirement and history pattern for the candidate, except for one less hierarchical level, but, a RoleTaskObservation clearly does not have an is-a relationship with RoleTask, unless I block my nose and rather use ObservedRoleTask. I would prefer to use the same pattern for both subject/course and task/observation structures, but I think that would force me to adopt a composition pattern for TrainingHistoryCourse. What is the wisdom here? Always inherit where possible and validated by a solid is-a association, or always favour composition wherever possible? 1 Client specified this to be called JobTitle, but he isn't writing the app, and a JobTitle is only one attribute of a Role. Authorization roles are handled by the DevExpress framework and its customization hooks, so there would be very little little confusion between a business Role in my domain objects and an authorization role in lower level, framework code.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >