Search Results

Search found 1493 results on 60 pages for 'inheritance'.

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

  • Propel Single Table Inheritance Issue

    - by lo_fye
    I have a table called "talk", which is defined as abstract in my schema.xml file. It generates 4 objects (1 per classkey): Comment, Rating, Review, Checkin It also generates TalkPeer, but I couldn't get it to generate the other 4 peers (CommentPeer, RatingPeer, ReviewPeer, CheckinPeer), so I created them by hand, and made them inherit from TalkPeer.php, which inherits from BaseTalkPeer. I then implemented getOMClass() in each of those peers. The problem is that when I do queries using the 4 peers, they return all 4 types of objects. That is, ReviewPeer will return Visits, Ratings, Comments, AND Reviews. Example: $c = new Criteria(); $c->add(RatingPeer::VALUE, 5, Criteria::GREATER_THAN); $positive_ratings = RatingPeer::doSelect($c); This returns all comments, ratings, reviews, & checkins that have a value 5. ReviewPeer should only return Review objects, and can't figure out how to do this. Do I actually have to go through and change all my criteria to manually specify the classkey? That seems a little pointless, since the Peer name already distinct. I don't want to have to customize each Peer. I should be able to customize JUST the TalkPeer, since they all inherit from it... I just can't figure out how. I tried changing doSelectStmt just in TalkPeer so that it automatically adds the CLASSKEY restriction to the Criteria. It almost works, but I get a: Fatal error: Cannot instantiate abstract class Talk in /models/om/BaseTalkPeer.php on line 503. Line 503 is in BaseTalkPeer::populateObjects(), and is the 3rd line below: $cls = TalkPeer::getOMClass($row, 0); $cls = substr('.'.$cls, strrpos('.'.$cls, '.') + 1); $obj = new $cls(); The docs talked about overriding BaseTalkPeer::populateObject(). I have a feeling that's my problem, but even after reading the source code, I still couldn't figure out how to get it to work. Here is what I tried in TalkPeer::doSelectStmt: public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { $keys = array('models.Visit'=>1,'models.Comment'=>2,'models.Rating'=>3,'models.Review'=>4); $class_name = self::getOMClass(); if(isset($keys[$class_name])) { //Talk itself is not a returnable type, so we must check $class_key = $keys[$class_name]; $criteria->add(TalkPeer::CLASS_KEY, $class_key); } return parent::doSelectStmt($criteria, $con = null); } Here is an example of my getOMClass method from ReviewPeer: public static function getOMClass() { return self::CLASSNAME_4; //aka 'talk.Review'; } Here is the relevant bit of my schema: <table name="talk" idMethod="native" abstract="true"> <column name="talk_pk" type="INTEGER" required="true" autoIncrement="true" primaryKey="true" /> <column name="class_key" type="INTEGER" required="true" default="" inheritance="single"> <inheritance key="1" class="Visit" extends="models.Talk" /> <inheritance key="2" class="Comment" extends="models.Talk" /> <inheritance key="3" class="Rating" extends="models.Talk" /> <inheritance key="4" class="Review" extends="models.Rating" /> </column> </table> P.S. - No, I can't upgrade from 1.3 to 1.4. There's just too much code that would need to be re-tested

    Read the article

  • How to refactor my design, if it seems to require multiple inheritance?

    - by Omega
    Recently I made a question about Java classes implementing methods from two sources (kinda like multiple inheritance). However, it was pointed out that this sort of need may be a sign of a design flaw. Hence, it is probably better to address my current design rather than trying to simulate multiple inheritance. Before tackling the actual problem, some background info about a particular mechanic in this framework: It is a simple game development framework. Several components allocate some memory (like pixel data), and it is necessary to get rid of it as soon as you don't need it. Sprites are an example of this. Anyway, I decided to implement something ala Manual-Reference-Counting from Objective-C. Certain classes, like Sprites, contain an internal counter, which is increased when you call retain(), and decreased on release(). Thus the Resource abstract class was created. Any subclass of this will obtain the retain() and release() implementations for free. When its count hits 0 (nobody is using this class), it will call the destroy() method. The subclass needs only to implement destroy(). This is because I don't want to rely on the Garbage Collector to get rid of unused pixel data. Game objects are all subclasses of the Node class - which is the main construction block, as it provides info such as position, size, rotation, etc. See, two classes are used often in my game. Sprites and Labels. Ah... but wait. Sprites contain pixel data, remember? And as such, they need to extend Resource. But this, of course, can't be done. Sprites ARE nodes, hence they must subclass Node. But heck, they are resources too. Why not making Resource an interface? Because I'd have to re-implement retain() and release(). I am avoiding this in virtue of not writing the same code over and over (remember that there are multiple classes that need this memory-management system). Why not composition? Because I'd still have to implement methods in Sprite (and similar classes) that essentially call the methods of Resource. I'd still be writing the same code over and over! What is your advice in this situation, then?

    Read the article

  • What is the exact problem with multiple inheritance?

    - by Totophil
    I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java and C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. What’s the matter with the multiple inheritance? Are there any concrete samples?

    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

  • Does Java not support multiple inheritance?

    - by user1720616
    Lets us take instances of two classes public abstract class Shapes { public abstract void draw(Graphics g); } public class Rectangle extends Shapes { public void draw(Graphics g) { //implementation of the method } } here the class Rectangle has extended class Shapes and implicitly it extends class Object.I know no other extension is possible but cant we call inheriting classes Shapes and Object multiple inheritance?(Since inheriting two classes is multiple inheritance from one perspective)

    Read the article

  • How should I plan the inheritance structure for my game?

    - by Eric Thoma
    I am trying to write a platform shooter in C++ with a really good class structure for robustness. The game itself is secondary; it is the learning process of writing it that is primary. I am implementing an inheritance tree for all of the objects in my game, but I find myself unsure on some decisions. One specific issue that it bugging me is this: I have an Actor that is simply defined as anything in the game world. Under Actor is Character. Both of these classes are abstract. Under Character is the Philosopher, who is the main character that the user commands. Also under Character is NPC, which uses an AI module with stock routines for friendly, enemy and (maybe) neutral alignments. So under NPC I want to have three subclasses: FriendlyNPC, EnemyNPC and NeutralNPC. These classes are not abstract, and will often be subclassed in order to make different types of NPC's, like Engineer, Scientist and the most evil Programmer. Still, if I want to implement a generic NPC named Kevin, it would nice to be able to put him in without making a new class for him. I could just instantiate a FriendlyNPC and pass some values for the AI machine and for the dialogue; that would be ideal. But what if Kevin is the one benevolent Programmer in the whole world? Now we must make a class for him (but what should it be called?). Now we have a character that should inherit from Programmer (as Kevin has all the same abilities but just uses the friendly AI functions) but also should inherit from FriendlyNPC. Programmer and FriendlyNPC branched away from each other on the inheritance tree, so inheriting from both of them would have conflicts, because some of the same functions have been implemented in different ways on the two of them. 1) Is there a better way to order these classes to avoid these conflicts? Having three subclasses; Friendly, Enemy and Neutral; from each type of NPC; Engineer, Scientist, and Programmer; would amount to a huge number of classes. I would share specific implementation details, but I am writing the game slowly, piece by piece, and so I haven't implemented past Character yet. 2) Is there a place where I can learn these programming paradigms? I am already trying to take advantage of some good design patterns, like MVC architecture and Mediator objects. The whole point of this project is to write something in good style. It is difficult to tell what should become a subclass and what should become a state (i.e. Friendly boolean v. Friendly class). Having many states slows down code with if statements and makes classes long and unwieldy. On the other hand, having a class for everything isn't practical. 3) Are there good rules of thumb or resources to learn more about this? 4) Finally, where does templating come in to this? How should I coordinate templates into my class structure? I have never actually taken advantage of templating honestly, but I hear that it increases modularity, which means good code.

    Read the article

  • WCF data services (OData), query with inheritance limitation?

    - by Mathieu Hétu
    Project: WCF Data service using internally EF4 CTP5 Code-First approach. I configured entities with inheritance (TPH). See previous question on this topic: Previous question about multiple entities- same table The mapping works well, and unit test over EF4 confirms that queries runs smoothly. My entities looks like this: ContactBase (abstract) Customer (inherits from ContactBase), this entity has also several Navigation properties toward other entities Resource (inherits from ContactBase) I have configured a discriminator, so both Customer and Resource map to the same table. Again, everythings works fine on the Ef4 point of view (unit tests all greens!) However, when exposing this DBContext over WCF Data services, I get: - CustomerBases sets exposed (Customers and Resources sets seems hidden, is it by design?) - When I query over Odata on Customers, I get this error: Navigation Properties are not supported on derived entity types. Entity Set 'ContactBases' has a instance of type 'CodeFirstNamespace.Customer', which is an derived entity type and has navigation properties. Please remove all the navigation properties from type 'CodeFirstNamespace.Customer'. Stacktrace: at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content, EpmSourcePathSegment currentSourceRoot) at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, ResourceType expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target) at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__b.MoveNext() at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer) at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved) at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved) at System.Data.Services.ResponseBodyWriter.Write(Stream stream) Seems like a limitation of WCF Data services... is it? Not much documentation can be found on the web about WCF Data services (OData) and inheritance specifications. How can I overpass this exception? I need these navigation properties on derived entities, and inheritance seems the only way to provide mapping of 2 entites on the same table with Ef4 CTP5... Any thoughts?

    Read the article

  • Question about Virtual Inheritance hierarchy

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 20 sizeof(C): 36 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; class D : public B, public C{ char h[ 3 ]; public: virtual void d(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; cout << "sizeof(D): " << sizeof( D ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • symfony + doctrine + inheritance, how to make them work?

    - by imac
    I am beginning to work with Symfony, I've found some documentation about inheritance. But also found this discouraging article, which make me doubt if Doctrine handles inheritance any good at all... Has anyone find a smart solution for inheritance in Symfony+Doctrine? As an example, I have already structured the database something like this: CREATE TABLE `poster` ( `poster_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, PRIMARY KEY (`poster_id`), UNIQUE KEY `id` (`poster_id`), ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `real_name` varchar(50) DEFAULT NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`), CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `poster` (`poster_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; From that, Doctrine generated this "schema.yml": Poster: connection: doctrine tableName: poster columns: poster_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: true user_name: type: string(50) fixed: false unsigned: false primary: false notnull: true autoincrement: false relations: Post: local: poster_id foreign: poster_id type: many User: local: poster_id foreign: user_id type: many Version: local: poster_id foreign: poster_id type: many User: connection: doctrine tableName: user columns: user_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: false real_name: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false relations: Poster: local: user_id foreign: poster_id type: one User creation for this structure with Doctrine auto-generated forms does not work. Any clue will be appreciated.

    Read the article

  • Entity Framework inheritance: TPT, TPH or none?

    - by silverfighter
    Hi, I am currently reading about the possibility about using inheritance with Entity Framework. Sometimes I use a approch to type data records and I am not sure if I would use TPT or TPH or none... For example... I have a ecommerce shop which adds shipping, billing, and delivery address I have a address table: RecordID AddressTypeID Street ZipCode City Country and a table AddressType RecordID AddressTypeDescription The table design differs to the gerneral design when people show off TPT or TPH... Does it make sense to think about inheritance an when having a approach like this.. I hope it makes sense... Thanks for any help...

    Read the article

  • Inheritance in Java

    - by Mandar
    Hello, recently I went through the inheritance concept. As we all know, in inheritance, superclass objects are created/initialized prior to subclass objects. So if we create an object of subclass, it will contain all the superclass information. But I got stuck at one point. Do the superclass and the subclass methods are present on separate call-stack? If it is so, is there any specific reason for same? If it is not so, why they don't appear on same call-stack? E.g. // Superclass class A { void play1( ) { // .... } } // Subclass class B extends A { void play2( ) { //..... } } Then does the above 2 methods i.e play1( ) and play2( ) appear on separate call stack? Thanks.

    Read the article

  • JPA Inheritance and Relations - Clarification question

    - by Michael
    Here the scenario: I have a unidirectional 1:N Relation from Person Entity to Address Entity. And a bidirectional 1:N Relation from User Entity to Vehicle Entity. Here is the Address class: @Entity public class Address implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) privat Long int ... The Vehicles Class: @Entity public class Vehicle implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne private User owner; ... @PreRemove protected void preRemove() { //this.owner.removeVehicle(this); } public Vehicle(User owner) { this.owner = owner; ... The Person Class: @Entity @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name="PERSON_TYP") public class Person implements Serializable { @Id protected String username; @OneToMany(cascade = CascadeType.ALL, orphanRemoval=true) @JoinTable(name = "USER_ADDRESS", joinColumns = @JoinColumn(name = "USERNAME"), inverseJoinColumns = @JoinColumn(name = "ADDRESS_ID")) protected List<Address> addresses; ... @PreRemove protected void prePersonRemove(){ this.addresses = null; } ... The User Class which is inherited from the Person class: @Entity @Table(name = "Users") @DiscriminatorValue("USER") public class User extends Person { @OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) private List<Vehicle> vehicles; ... When I try to delete a User who has an address I have to use orphanremoval=true on the corresponding relation (see above) and the preRemove function where the address List is set to null. Otherwise (no orphanremoval and adress list not set to null) a foreign key contraint fails. When i try to delete a user who has an vehicle a concurrent Acces Exception is thrown when do not uncomment the "this.owner.removeVehicle(this);" in the preRemove Function of the vehicle. The thing i do not understand is that before i used this inheritance there was only a User class which had all relations: @Entity @Table(name = "Users") public class User implements Serializable { @Id protected String username; @OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) private List<Vehicle> vehicles; @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "USER_ADDRESS", joinColumns = @JoinColumn(name = "USERNAME") inverseJoinColumns = @JoinColumn(name = "ADDRESS_ID")) ptivate List<Address> addresses; ... No orphanremoval, and the vehicle class has used the uncommented statement above in its preRemove function. And - I could delte a user who has an address and i could delte a user who has a vehicle. So why doesn't everything work without changes when i use inheritance? I use JPA 2.0, EclipseLink 2.0.2, MySQL 5.1.x and Netbeans 6.8

    Read the article

  • Inheritance or identifier

    - by Lina
    Hi! Does anyone here have opinions about when to user inheritance and when to use an identifier instead? Inheritance example: class Animal { public int Name { get; set; } } class Dog : Animal {} class Cat : Animal {} Identifier example: class Animal { public int Name { get; set; } public AnimalType { get; set; } } In what situations should i prefer which solution and what are the pros and cons for them? /Lina

    Read the article

  • Linq to SQL inheritance and Table per Class - approach needed for multiple roles

    - by Ash Machine
    I am using L2S and an inheritance model for mapping Persons against certain roles. Guy Burstein's excellent blog post explains how to accomplish this: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx However, I have a specific case where a Person has multiple roles. For example 'Jane Doe' is a Contact and a Programmer. In this model, she would need two rows in the People table, one as Contact (PersonType = 1) and one as Programmer (PersonType = 3). If she changes her last name, and that update happens in her role as Contact, I would need to change all instances of 'Jane Doe' to reflect the name change everywhere. What sort of best approach (improved data structure) could be used to change last name within all roles? Finally, I am hoping to avoid overriding each general form update events to include all instances, but that may be the only way. Any suggestions or approaches appreciated.

    Read the article

  • Table per subclass inheritance relationship: How to query against the Parent class without loading a

    - by Arthur Ronald F D Garcia
    Suppose a Table per subclass inheritance relationship which can be described bellow (From wikibooks.org - see here) Notice Parent class is not abstract @Entity @Inheritance(strategy=InheritanceType.JOINED) public class Project { @Id private long id; // Other properties } @Entity @Table(name="LARGEPROJECT") public class LargeProject extends Project { private BigDecimal budget; } @Entity @Table(name="SMALLPROJECT") public class SmallProject extends Project { } I have a scenario where i just need to retrieve the Parent class. Because of performance issues, What should i do to run a HQL query in order to retrieve the Parent class and just the Parent class without loading any subclass ???

    Read the article

  • Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?

    - by Brettetete
    Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture. So I want to do create an architecture for NPCs in a video-game. It is a Realtime Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack(). Examples: Worker can Build() and Farm() Warrior can Attack() Citizen can Build(), Farm() and Attack() Fisherman can Farm() and Attack() I hope everything is clear so far. So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect. What would be a good programmatic architecture for my different kinds of NPCs? Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle. So I can have methods like WalkTo(x,y) in my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack()) Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..). Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild, .. I think it is clear what I want to express. But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality. I do use C# as programming language. So multiple inheritance isn't an opinion here. Means: Having extra base classes like Fisherman : Farmer, Attacker won't work.

    Read the article

  • C++ Exceptions and Inheritance from std::exception

    - by fbrereto
    Given this sample code: #include <iostream> #include <stdexcept> class my_exception_t : std::exception { public: explicit my_exception_t() { } virtual const char* what() const throw() { return "Hello, world!"; } }; int main() { try { throw my_exception_t(); } catch (const std::exception& error) { std::cerr << "Exception: " << error.what() << std::endl; } catch (...) { std::cerr << "Exception: unknown" << std::endl; } return 0; } I get the following output: Exception: unknown Yet simply making the inheritance of my_exception_t from std::exception public, I get the following output: Exception: Hello, world! Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.

    Read the article

  • How does virtual inheritance solve the diamond problem?

    - by cambr
    class A { public: void eat(){ cout<<"A";} }; class B: virtual public A { public: void eat(){ cout<<"B";} }; class C: virtual public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main(){ A *a = new D(); a->eat(); } I understand the diamond problem, and above piece of code does not have that problem. How exatly does virtual inheritance solve the problem? What I understand: When I say A *a = new D();, the compiler wants to know if an object of type D can be assigned to a pointer of type A, but it has two paths that it can follow, but cannot decide by itself. So, how does virtual inheritance resolve the issue (help compiler take the decision)?

    Read the article

  • Active Record two belongs_to calls or single table inheritance

    - by ethyreal
    In linking a sports event to two teams, at first this seemed to make sense: events - id:integer - integer:home_team_id - integer:away_team_id teams - integer:id - string:name However I am troubled by how I would link that up in the active record model: class Event belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id" belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id" end Is that the best solution? In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. If I did go with single table inheritance I wouldn't want each team to belong_to an event so would this work? # app/models/event.rb class Event < ActiveRecord::Base belongs_to :home_team belongs_to :away_team end # app/models/team.rb class Team < ActiveRecord::Base has_many :teams end # app/models/home_team.rb class HomeTeam < Team end # app/models/away_team.rb class AwayTeam < Team end I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event. event_teams - integer:event_id - integer:team_id - boolean:is_home Is there a cleaner more semantic way for making these associations in active record? or is one of these solutions the best choice? Thanks

    Read the article

  • Inheritance of closure objects and overriding of methods

    - by bobikk
    I need to extend a class, which is encapsulated in a closure. This base class is following: var PageController = (function(){ // private static variable var _current_view; return function(request, new_view) { ... // priveleged public function, which has access to the _current_view this.execute = function() { alert("PageController::execute"); } } })(); Inheritance is realised using the following function: function extend(subClass, superClass){ var F = function(){ }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; StartController.cache = ''; if (superClass.prototype.constructor == Object.prototype.constructor) { superClass.prototype.constructor = superClass; } } I subclass the PageController: var StartController = function(request){ // calling the constructor of the super class StartController.superclass.constructor.call(this, request, 'start-view'); } // extending the objects extend(StartController, PageController); // overriding the PageController::execute StartController.prototype.execute = function() { alert('StartController::execute'); } Inheritance is working. I can call every PageController's method from StartController's instance. However, method overriding doesn't work: var startCont = new StartController(); startCont.execute(); alerts "PageController::execute". How should I override this method?

    Read the article

  • @PrePersist with entity inheritance

    - by gerry
    I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following: _the 'base' class with the annotated updateDates() method: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Base implements Serializable{ ... @Id @GeneratedValue protected Long id; ... @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastModificationDate; ... public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } ... @PrePersist protected void updateDates() { if (creationDate == null) { creationDate = new Date(); } lastModificationDate = new Date(); } } _ now the 'Child' class that should inherit all methods "and annotations" from the base class: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Entity { ... // additional attributes @Column(nullable=false) protected String value; ... // additional getters, setters ... } If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception: MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database. What is wrong with my code?

    Read the article

  • Programming exercises in Java inheritance for intern

    - by Tenner
    I work for a small software development team, working primarily in Java, for a very large company. Our new intern showed up sight-unseen (not uncommon in my company). He has some C++ experience but no Java. Worse, he's never worked with inheritance in C++. Our code has a great deal of abstraction and a heavy reliance on inheritance. We need to get him up to speed as quickly as possible. Of course the rest of the team is busy, and so we can't take the time out of our day to teach a one-student 200-level CS course. Instead, I'd like to give him an actual programming project to work on which highlights how classes, interfaces, method overrides, etc. work. I've had him look at Project Euler, but most of the solutions end up being procedural, and not object-oriented programs. Do any of you have any somewhat-straightforward (and relatively quick) projects which you would give to an intern in this situation? Or, any recent (or current) students have a school project they'd be willing to share? Anyone else had this experience?

    Read the article

  • Rails Model inheritance in forms

    - by Tiago
    I'm doing a reporting system for my app. I created a model ReportKind for example, but as I can report a lot of stuff, I wanted to make different groups of report kinds. Since they share a lot of behavior, I'm trying to use inheritance. So I have the main model: model ReportKind << ActiveRecord::Base end and created for example: model UserReportKind << ReportKind end In my table report_kinds I've the type column, and until here its all working. My problem is in the forms/controllers. When I do a ReportKind.new, my form is build with the '*report_kind*' prefix. If a get a UserReportKind, even through a ReportKind.find, the form will build the 'user_report_kind' prefix. This mess everything in the controllers, since sometimes I'll have params[:report_kind], sometimes params[:user_report_kind], and so on for every other inheritance I made. Is there anyway to force it to aways use the 'report_kind' prefix? Also I had to force the attribute 'type' in the controller, because it didn't get the value direct from the form, is there a pretty way to do this? Routing was another problem, since it was trying to build routes based in the inherited models names. I overcome that by adding the other models in routes pointing to the same controller.

    Read the article

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