Search Results

Search found 45849 results on 1834 pages for 'abstract class'.

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

  • UML Class Diagram: Abstract or Interface?

    - by J Smith
    I am modeling a class diagram and have spotted an opportunity to simplify it slightly. What I want to know is, would this it be better to implement an abstract class or an interface? The scenario is this, I have the classes: Artist Genre Album Song All of which share the methods getName, setName, and getCount (playcount that is). Would it be best to create an abstract 'Music' class with the aforementioned abstract methods, or should I create an interface, since the classes that implement the interface have to include all of the interface's methods (I think, correct me if I'm wrong). I hope I've given enough detail, please ask questions if I haven't. Thanks!

    Read the article

  • c++ casting base class to derived class mess

    - by alan2here
    If I were to create a base class called base and derived classes called derived_1, derived_2 etc... I use a collection of instances of the base class, then when I retrieved an element and tried to use it I would find that C++ thinks it's type is that of the base class, probably because I retrieved it from a std::vector of base. Which is a problem when I want to use features that only exist for the specific derived class who's type I knew this object was when I put it into the vector. So I cast the element into the type it is supposed to be and found this wouldn't work. (derived_3)obj_to_be_fixed; And remembered that it's a pointer thing. After some tweaking this now worked. *((derived_3*)&obj_to_be_fixed); Is this right or is there for example an abc_cast() function that does it with less mess?

    Read the article

  • class hierarchy design for small java project

    - by user523956
    I have written a java code which does following:- Main goal is to fetch emails from (inbox, spam) folders and store them in database. It fetches emails from gmail,gmx,web.de,yahoo and Hotmail. Following attributes are stored in mysql database. Slno, messagedigest, messageid, foldername, dateandtime, receiver, sender, subject, cc, size and emlfile. For gmail,gmy and web.de, I have used javamail API, because email form it can be fetched with IMAP. For yahoo and hotmail, I have used html parser and httpclient to fetch emails form spam folder and for inbox folder, I have used pop3 javamail API. I want to have proper class hierarchy which makes my code efficient and easily reusable. As of now I have designed class hierarchy as below: I am sure it can still be improved. So I would like to have different opinions on it. I have following classes and methods as of now. MainController:- Here I pass emailid, password and foldername from which emails have to be fetched. Abstract Class :-EmailProtocol Abstract Methods of it (All methods except executeParser contains method definition):- connectImap() // used by gmx,gmail and web.de email ids connectPop3() // used by hotmail and yahoo to fetch emails of inbox folder createMessageDigest // used by every email provider(gmx, gmail,web.de,yahoo,hotmail) establishDBConnection // used by every email emailAlreadyExists // used by every email which checks whether email already exists in db or not, if not then store it. storeemailproperties // used by every email to store emails properties to mysql database executeParser // nothing written in it. Overwridden and used by just hotmail and yahoo to fetch emails form spam folder. Imap extends EmailProtocol (nothing in it. But I have to have it to access methods of EmailProtocol. This is used to fetch emails from gmail,gmx and web.de) I know this is really a bad way but don't know how to do it other way. Hotmsil extends EmailProtocol Methods:- executeParser() :- This is used by just hotmail email id. fetchjunkemails() :- This is also very specific for only hotmail email id. Yahoo extends EmailProtocol Methods:- executeParser() storeEmailtotemptable() MoveEmailtoInbox() getFoldername() nullorEquals() All above methods are specific for yahoo email id. public DateTimeFormat(class) format() //this formats datetime of gmax,gmail and web.de emails. formatYahoodate //this formats datetime of yahoo email. formatHotmaildate // this formats datetime of hotmail email. public StringFormat ConvertStreamToString() // Accessed by every class except DateTimeFormat class. formatFromTo() // Accessed by every class except DateTimeFormat class. public Class CheckDatabaseExistance public static void checkForDatabaseTablesAvailability() (This method checks at the beginnning whether database and required tables exist in mysql or not. if not it creates them) Please see code of my MainController class so that You can have an idea about how I use different classes. public class MainController { public static void main(String[] args) throws Exception { ArrayList<String> web_de_folders = new ArrayList<String>(); web_de_folders.add("INBOX"); web_de_folders.add("Unbekannt"); web_de_folders.add("Spam"); web_de_folders.add("OUTBOX"); web_de_folders.add("SENT"); web_de_folders.add("DRAFTS"); web_de_folders.add("TRASH"); web_de_folders.add("Trash"); ArrayList<String> gmx_folders = new ArrayList<String>(); gmx_folders.add("INBOX"); gmx_folders.add("Archiv"); gmx_folders.add("Entwürfe"); gmx_folders.add("Gelöscht"); gmx_folders.add("Gesendet"); gmx_folders.add("Spamverdacht"); gmx_folders.add("Trash"); ArrayList<String> gmail_folders = new ArrayList<String>(); gmail_folders.add("Inbox"); gmail_folders.add("[Google Mail]/Spam"); gmail_folders.add("[Google Mail]/Trash"); gmail_folders.add("[Google Mail]/Sent Mail"); ArrayList<String> pop3_folders = new ArrayList<String>(); pop3_folders.add("INBOX"); CheckDatabaseExistance.checkForDatabaseTablesAvailability(); EmailProtocol imap = new Imap(); System.out.println("CHECKING FOR NEW EMAILS IN WEB.DE...(IMAP)"); System.out.println("*********************************************************************************"); imap.connectImap("[email protected]", "pwd", web_de_folders); System.out.println("\nCHECKING FOR NEW EMAILS IN GMX.DE...(IMAP)"); System.out.println("*********************************************************************************"); imap.connectImap("[email protected]", "pwd", gmx_folders); System.out.println("\nCHECKING FOR NEW EMAILS IN GMAIL...(IMAP)"); System.out.println("*********************************************************************************"); imap.connectImap("[email protected]", "pwd", gmail_folders); EmailProtocol yahoo = new Yahoo(); Yahoo y=new Yahoo(); System.out.println("\nEXECUTING YAHOO PARSER"); System.out.println("*********************************************************************************"); y.executeParser("http://de.mc1321.mail.yahoo.com/mc/welcome?ymv=0","[email protected]","pwd"); System.out.println("\nCHECKING FOR NEW EMAILS IN INBOX OF YAHOO (POP3)"); System.out.println("*********************************************************************************"); yahoo.connectPop3("[email protected]","pwd",pop3_folders); System.out.println("\nCHECKING FOR NEW EMAILS IN INBOX OF HOTMAIL (POP3)"); System.out.println("*********************************************************************************"); yahoo.connectPop3("[email protected]","pwd",pop3_folders); EmailProtocol hotmail = new Hotmail(); Hotmail h=new Hotmail(); System.out.println("\nEXECUTING HOTMAIL PARSER"); System.out.println("*********************************************************************************"); h.executeParser("https://login.live.com/ppsecure/post.srf","[email protected]","pwd"); } } I have kept DatetimeFormat and StringFormat class public so that I can access its public methods by just (DatetimeFormat.formatYahoodate for e.g. from different methods). This is the first time I have developed something in java. It serves its purpose but of course code is still not so efficient I think. I need your suggestions on this project.

    Read the article

  • Switching from abstract class to interface

    - by nischayn22
    I have an abstract class which has all abstract methods except one which constructs objects of the subclasses. Now my mentor asked me to move this abstract class to an interface. Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now? Also, I read somewhere that interfaces are more efficient than abstract classes. Is this true? Here's an example of my classes abstract class Animal { //many abstract methods getAnimalobject(some parameter) { return //appropriate subclass } } class Dog extends Animal {} class Elephant extends Animal {}

    Read the article

  • Abstract Base Class or Class?

    - by Mohit Deshpande
    For my semester project, my team and I are supposed to make a .jar file (library, not runnable) that contains a game development framework and demonstrate the concepts of OOP. Its supposed to be a FRAMEWORK and another team is supposed to use our framework and vice-versa. So I want to know how we should start. We thought of several approaches: 1. Start with a plain class public class Enemy { public Enemy(int x, int y, int health, int attack, ...) { ... } ... } public class UserDefinedClass extends Enemy { ... } 2. Start with an abstract class that user-defined enemies have to inherit abstract members public abstract class Enemy { public Enemy(int x, int y, int health, int attack, ...) { ... } public abstract void draw(); public abstract void destroy(); ... } public class UserDefinedClass extends Enemy { ... public void draw() { ... } public void destroy() { ... } } 3. Create a super ABC (Abstract Base Class) that ALL inherit from public abstract class VectorEntity { ... } public abstract class Enemy extends VectorEntity { ... } public class Player extends VectorEntity { ... } public class UserDefinedClass extends Enemy { ... } Which should I use? Or is there a better way?

    Read the article

  • Abstract class + Inheritance vs Interface

    - by RealityDysfunction
    Hello fellow programmers, I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:" abstract class CloneableType { public abstract object Clone(); } Then you cannot do this: public class MiniVan : Car, CloneableType {} This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so: public interface ICloneable { object Clone(); } My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class - Car class - Minivan Class. What do you think? Thanks.

    Read the article

  • C++: Create abstract class with abstract method and override the method in a subclass

    - by Martijn Courteaux
    Hi, How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look? In Java it would look like this: abstract class GameObject { public abstract void update(); public abstract void paint(Graphics g); } class Player extends GameObject { @Override public void update() { // ... } @Override public void paint(Graphics g) { // ... } } // In my game loop: for (int i = 0; i < objects.size(); i++) { objects.get(i).update(); } for (int i = 0; i < objects.size(); i++) { objects.get(i).paint(g); } Translating this code to C++ is enough for me.

    Read the article

  • Abstract exception super type

    - by marcof
    If throwing System.Exception is considered so bad, why wasn't Exception made abstract in the first place? That way, it would not be possible to call: throw new Exception("Error occurred."); This would enforce using derived exceptions to provide more details about the error that occurred. For example, when I want to provide a custom exception hierarchy for a library, I usually declare an abstract base class for my exceptions: public abstract class CustomExceptionBase : Exception { /* some stuff here */ } And then some derived exception with a more specific purpose: public class DerivedCustomException : CustomExceptionBase { /* some more specific stuff here */ } Then when calling any library method, one could have this generic try/catch block to directly catch any error coming from the library: try { /* library calls here */ } catch (CustomExceptionBase ex) { /* exception handling */ } Is this a good practice? Would it be good if Exception was made abstract? EDIT : My point here is that even if an exception class is abstract, you can still catch it in a catch-all block. Making it abstract is only a way to forbid programmers to throw a "super-wide" exception. Usually, when you voluntarily throw an exception, you should know what type it is and why it happened. Thus enforcing to throw a more specific exception type.

    Read the article

  • abstract class extends abstract class in php?

    - by user151841
    I am working on a simple abstract database class. In my usage of this class, I'll want to have some instance be a singleton. I was thinking of having a abstract class that is not a singleton, and then extend it into another abstract class that is a singleton. Is this possible? Recommended?

    Read the article

  • Why can't you call abstract functions from abstract classes in PHP?

    - by incrediman
    I've set up an abstract parent class, and a concrete class which extends it. Why can the parent class not call the abstract function? //foo.php <?php abstract class AbstractFoo{ abstract public static function foo(); public static function getFoo(){ return self::foo();//line 5 } } class ConcreteFoo extends AbstractFoo{ public static function foo(){ return "bar"; } } echo ConcreteFoo::getFoo(); ?> Error: Fatal error: Cannot call abstract method AbstractFoo::foo() in foo.php on line 5

    Read the article

  • Java - abstract class, equals(), and two subclasses

    - by msr
    Hello, I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration. However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method? In summary, this is the code I have: public abstract class Xpto { } public class Person extends Xpto{ protected String name; public Person(String name){ this.name = name; } public boolean equals(Person p){ System.out.println("Person equals()?"); return this.name.compareTo(p.name) == 0 ? true : false; } } public class Car extends Xpto{ protected String registration; public Car(String registration){ this.registration = registration; } public boolean equals(Car car){ System.out.println("Car equals()?"); return this.registration.compareTo(car.registration) == 0 ? true : false; } } public class Teste { public static void foo(Xpto xpto1, Xpto xpto2){ if(xpto1.equals(xpto2)) System.out.println("xpto1.equals(xpto2) -> true"); else System.out.println("xpto1.equals(xpto2) -> false"); } public static void main(String argv[]){ Car c1 = new Car("ABC"); Car c2 = new Car("DEF"); Person p1 = new Person("Manel"); Person p2 = new Person("Manel"); foo(p1,p2); } }

    Read the article

  • What are the differences between abstract classes, interfaces, and when to use them

    - by user66662
    Recently I have started to wrap my head around OOP, and I am now to the point where the more I read about the differences between Abstract classes and Interfaces the more confused I become. So far, neither can be instantiated. Interfaces are more or less structural blueprints that determine the skeleton and abstracts are different by being able to partially develop code. I would like to learn more about these through my specific situation. Here is a link to my first question if you would like a little more background information: What is a good design model for my new class? Here are two classes I created: class Ad { $title; $description $price; function get_data($website){ } function validate_price(){ } } class calendar_event { $title; $description $start_date; function get_data($website){ //guts } function validate_dates(){ //guts } } So, as you can see these classes are almost identical. Not shown here, but there are other functions, like get_zip(), save_to_database() that are common across my classes. I have also added other classes Cars and Pets which have all the common methods and of course properties specific to those objects (mileage, weight, for example). Now I have violated the DRY principle and I am managing and changing the same code across multiple files. I intend on having more classes like boats, horses, or whatever. So is this where I would use an interface or abstract class? From what I understand about abstract classes I would use a super class as a template with all of the common elements built into the abstract class, and then add only the items specifically needed in future classes. For example: abstract class content { $title; $description function get_data($website){ } function common_function2() { } function common_function3() { } } class calendar_event extends content { $start_date; function validate_dates(){ } } Or would I use an interface and, because these are so similar, create a structure that each of the subclasses are forced to use for integrity reasons, and leave it up to the end developer who fleshes out that class to be responsible for each of the details of even the common functions. my thinking there is that some 'common' functions may need to be tweaked in the future for the needs of their specific class. Despite all that above, if you believe I am misunderstanding the what and why of abstracts and interfaces altogether, by all means let a valid answer to be stop thinking in this direction and suggest the proper way to move forward! Thanks!

    Read the article

  • Class Design and Structure Online Web Store

    - by Phorce
    I hope I have asked this in the right forum. Basically, we're designing an Online Store and I am designing the class structure for ordering a product and want some clarification on what I have so far: So a customer comes, selects their product, chooses the quantity and selects 'Purchase' (I am using the Facade Pattern - So subsystems execute when this action is performed). My class structure: < Order > < Product > <Customer > There is no inheritance, more Association < Order has < Product , < Customer has < Order . Does this structure look ok? I've noticed that I don't handle the "Quantity" separately, I was just going to add this into the "Product" class, but, do you think it should be a class of it's own? Hope someone can help.

    Read the article

  • 'abstract class' versus 'normal class' for a reusable library

    - by Greg
    I'm developing a reusable library and have been creating abstract classes, so the client can then extend from these. QUESTION: Is there any reason in fact I should use an abstract class here as opposed to just a normal class? Note - Have already decided I do not want to use interfaces as I want to include actual default methods in my library so the client using it doesn't have to write the code.

    Read the article

  • UML - Class Diagrams Order -> Products

    - by Phorce
    I have a class diagram that is like this: < Order > (1) CAN HAVE (M) < products > But therefore "Order" has the following: Order_Id Customer_Id Order_date_day Order_date_month Order_date_yeah But I do not know how it would handle the Products? Because, I couldn't have "ProductID" because that would mean that each item in this class would have to have a separate instance for each product (E.g. someone ordered 100 products, but only placed 1 order). Could I have an Product object in class Order? If so, how do you represent that in UML? Thank you

    Read the article

  • Followup: Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I asked a question at Python 2.6, 3 abstract base class misunderstanding. My problem was that python abstract base classes didn't work quite the way I expected them to. There was some discussion in the comments about why I would want to use ABCs at all, and Alex Martelli provided an excellent answer on why my use didn't work and how to accomplish what I wanted. Here I'd like to address why one might want to use ABCs, and show my test code implementation based on Alex's answer. tl;dr: Code after the 16th paragraph. In the discussion on the original post, statements were made along the lines that you don't need ABCs in Python, and that ABCs don't do anything and are therefore not real classes; they're merely interface definitions. An abstract base class is just a tool in your tool box. It's a design tool that's been around for many years, and a programming tool that is explicitly available in many programming languages. It can be implemented manually in languages that don't provide it. An ABC is always a real class, even when it doesn't do anything but define an interface, because specifying the interface is what an ABC does. If that was all an ABC could do, that would be enough reason to have it in your toolbox, but in Python and some other languages they can do more. The basic reason to use an ABC is when you have a number of classes that all do the same thing (have the same interface) but do it differently, and you want to guarantee that that complete interface is implemented in all objects. A user of your classes can rely on the interface being completely implemented in all classes. You can maintain this guarantee manually. Over time you may succeed. Or you might forget something. Before Python had ABCs you could guarantee it semi-manually, by throwing NotImplementedError in all the base class's interface methods; you must implement these methods in derived classes. This is only a partial solution, because you can still instantiate such a base class. A more complete solution is to use ABCs as provided in Python 2.6 and above. Template methods and other wrinkles and patterns are ideas whose implementation can be made easier with full-citizen ABCs. Another idea in the comments was that Python doesn't need ABCs (understood as a class that only defines an interface) because it has multiple inheritance. The implied reference there seems to be Java and its single inheritance. In Java you "get around" single inheritance by inheriting from one or more interfaces. Java uses the word "interface" in two ways. A "Java interface" is a class with method signatures but no implementations. The methods are the interface's "interface" in the more general, non-Java sense of the word. Yes, Python has multiple inheritance, so you don't need Java-like "interfaces" (ABCs) merely to provide sets of interface methods to a class. But that's not the only reason in software development to use ABCs. Most generally, you use an ABC to specify an interface (set of methods) that will likely be implemented differently in different derived classes, yet that all derived classes must have. Additionally, there may be no sensible default implementation for the base class to provide. Finally, even an ABC with almost no interface is still useful. We use something like it when we have multiple except clauses for a try. Many exceptions have exactly the same interface, with only two differences: the exception's string value, and the actual class of the exception. In many exception clauses we use nothing about the exception except its class to decide what to do; catching one type of exception we do one thing, and another except clause catching a different exception does another thing. According to the exception module's doc page, BaseException is not intended to be derived by any user defined exceptions. If ABCs had been a first class Python concept from the beginning, it's easy to imagine BaseException being specified as an ABC. But enough of that. Here's some 2.6 code that demonstrates how to use ABCs, and how to specify a list-like ABC. Examples are run in ipython, which I like much better than the python shell for day to day work; I only wish it was available for python3. Your basic 2.6 ABC: from abc import ABCMeta, abstractmethod class Super(): __metaclass__ = ABCMeta @abstractmethod def method1(self): pass Test it (in ipython, python shell would be similar): In [2]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 Notice the end of the last line, where the TypeError exception tells us that method1 has not been implemented ("abstract methods method1"). That was the method designated as @abstractmethod in the preceding code. Create a subclass that inherits Super, implement method1 in the subclass and you're done. My problem, which caused me to ask the original question, was how to specify an ABC that itself defines a list interface. My naive solution was to make an ABC as above, and in the inheritance parentheses say (list). My assumption was that the class would still be abstract (can't instantiate it), and would be a list. That was wrong; inheriting from list made the class concrete, despite the abstract bits in the class definition. Alex suggested inheriting from collections.MutableSequence, which is abstract (and so doesn't make the class concrete) and list-like. I used collections.Sequence, which is also abstract but has a shorter interface and so was quicker to implement. First, Super derived from Sequence, with nothing extra: from abc import abstractmethod from collections import Sequence class Super(Sequence): pass Test it: In [6]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods __getitem__, __len__ We can't instantiate it. A list-like full-citizen ABC; yea! Again, notice in the last line that TypeError tells us why we can't instantiate it: __getitem__ and __len__ are abstract methods. They come from collections.Sequence. But, I want a bunch of subclasses that all act like immutable lists (which collections.Sequence essentially is), and that have their own implementations of my added interface methods. In particular, I don't want to implement my own list code, Python already did that for me. So first, let's implement the missing Sequence methods, in terms of Python's list type, so that all subclasses act as lists (Sequences). First let's see the signatures of the missing abstract methods: In [12]: help(Sequence.__getitem__) Help on method __getitem__ in module _abcoll: __getitem__(self, index) unbound _abcoll.Sequence method (END) In [14]: help(Sequence.__len__) Help on method __len__ in module _abcoll: __len__(self) unbound _abcoll.Sequence method (END) __getitem__ takes an index, and __len__ takes nothing. And the implementation (so far) is: from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() Test it: In [34]: a = Super() In [35]: a Out[35]: [] In [36]: print a [] In [37]: len(a) Out[37]: 0 In [38]: a[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() /home/aaron/projects/test/test.py in __getitem__(self, index) 10 # Abstract method in Sequence, implemented in terms of list. 11 def __getitem__(self, index): ---> 12 return self._list.__getitem__(index) 13 14 # Abstract method in Sequence, implemented in terms of list. IndexError: list index out of range Just like a list. It's not abstract (for the moment) because we implemented both of Sequence's abstract methods. Now I want to add my bit of interface, which will be abstract in Super and therefore required to implement in any subclasses. And we'll cut to the chase and add subclasses that inherit from our ABC Super. from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() @abstractmethod def method1(): pass class Sub0(Super): pass class Sub1(Super): def __init__(self): self._list = [1, 2, 3] def method1(self): return [x**2 for x in self._list] def method2(self): return [x/2.0 for x in self._list] class Sub2(Super): def __init__(self): self._list = [10, 20, 30, 40] def method1(self): return [x+2 for x in self._list] We've added a new abstract method to Super, method1. This makes Super abstract again. A new class Sub0 which inherits from Super but does not implement method1, so it's also an ABC. Two new classes Sub1 and Sub2, which both inherit from Super. They both implement method1 from Super, so they're not abstract. Both implementations of method1 are different. Sub1 and Sub2 also both initialize themselves differently; in real life they might initialize themselves wildly differently. So you have two subclasses which both "is a" Super (they both implement Super's required interface) although their implementations are different. Also remember that Super, although an ABC, provides four non-abstract methods. So Super provides two things to subclasses: an implementation of collections.Sequence, and an additional abstract interface (the one abstract method) that subclasses must implement. Also, class Sub1 implements an additional method, method2, which is not part of Super's interface. Sub1 "is a" Super, but it also has additional capabilities. Test it: In [52]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 In [53]: a = Sub0() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Sub0 with abstract methods method1 In [54]: a = Sub1() In [55]: a Out[55]: [1, 2, 3] In [56]: b = Sub2() In [57]: b Out[57]: [10, 20, 30, 40] In [58]: print a, b [1, 2, 3] [10, 20, 30, 40] In [59]: a, b Out[59]: ([1, 2, 3], [10, 20, 30, 40]) In [60]: a.method1() Out[60]: [1, 4, 9] In [61]: b.method1() Out[61]: [12, 22, 32, 42] In [62]: a.method2() Out[62]: [0.5, 1.0, 1.5] [63]: a[:2] Out[63]: [1, 2] In [64]: a[0] = 5 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: 'Sub1' object does not support item assignment Super and Sub0 are abstract and can't be instantiated (lines 52 and 53). Sub1 and Sub2 are concrete and have an immutable Sequence interface (54 through 59). Sub1 and Sub2 are instantiated differently, and their method1 implementations are different (60, 61). Sub1 includes an additional method2, beyond what's required by Super (62). Any concrete Super acts like a list/Sequence (63). A collections.Sequence is immutable (64). Finally, a wart: In [65]: a._list Out[65]: [1, 2, 3] In [66]: a._list = [] In [67]: a Out[67]: [] Super._list is spelled with a single underscore. Double underscore would have protected it from this last bit, but would have broken the implementation of methods in subclasses. Not sure why; I think because double underscore is private, and private means private. So ultimately this whole scheme relies on a gentleman's agreement not to reach in and muck with Super._list directly, as in line 65 above. Would love to know if there's a safer way to do that.

    Read the article

  • Class Design for special business rules

    - by Samuel Front
    I'm developing an application that allows people to place custom manufacturing orders. However, while most require similar paperwork, some of them have custom paperwork that only they require. My current class design has a Manufacturer class, of which of one of the member variables is an array of RequiredSubmission objects. However, there are two issues that I am somewhat concerned about. First, some manufacturers are willing to accept either a standard form or their own custom form. I'm thinking of storing this in the RequiredSubmission object, with an array of alternate forms that are a valid substitute. I'm not sure that this is ideal, however. The major issue, however, is that some manufacturers have deadline cycles. For example, forms A, B and C have to be delivered by January 1, while payment must be rendered by January 10. If you miss those, you'll have to wait until the next cycle. I'm not exactly sure how I can get this to work with my existing classes—how can I say "this set of dates all belong to the same cycle, with date A for form A, date B for form B, etc." I would greatly appreciate any insights on how to best design these classes.

    Read the article

  • Nested class - calling the nested class from the parent class

    - by insanepaul
    I have a class whereby a method calls a nested class. I want to access the parent class properties from within the nested class. public class ParentClass { private x; private y; private z; something.something = new ChildClass public class ChildClass { need to get x, y and z; } } How do I access x,y and z from within the child class. Something to do with referencing the parent class but how? }

    Read the article

  • Help to understand the abstract factory pattern

    - by Chobeat
    I'm learning the 23 design patterns of the GoF. I think I've found a way to understand and simplify how the Abstract Factory works but I would like to know if this is a correct assumption or if I am wrong. What I want to know is if we can see the result of the Abstract Factory method as a matrix of possible products where there's a Product for every "Concrete Factory" x "AbstractProduct" where the Concrete Factory is a single implementation among the implementations of an AbstractFactory and an AbstractProduct is an interface among the interfaces to create Products. Is this correct or am I missing something?

    Read the article

  • Why should I declare a class as an abstract class?

    - by Pied Piper
    I know the syntax, rules applied to abstract class and I want know usage of an abstract class Abstract class can not be instantiated directly but can be extended by other class What is the advantage of doing so? How it is different from an Interface? I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class? I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java. In which situations I should declare class as an abstract class? What is benefits of that?

    Read the article

  • Static classes in PHP via abstract keyword?

    - by Boldewyn
    According to the PHP manual, a class like this: abstract class Example {} cannot be instantiated. If I need a class without instance, e.g. for a registry pattern: class Registry {} // and later: echo Registry::$someValue; would it be considered good style to simply declare the class as abstract? If not, what are the advantages of hiding the constructor as protected method compared to an abstract class? Rationale for asking: As far as I see it, it could a bit of feature abuse, since the manual refers to abstract classes more as like blueprints for later classes with instantiation possibility.

    Read the article

  • Can You Have "Empty" Abstract/Classes?

    - by ShrimpCrackers
    Of course you can, I'm just wondering if it's rational to design in such a way. I'm making a breakout clone and was doing some class design. I wanted to use inheritance, even though I don't have to, to apply what I've learned in C++. I was thinking about class design and came up with something like this: GameObject - base class (consists of data members like x and y offsets, and a vector of SDL_Surface* MovableObject : GameObject - abstract class + derived class of GameObject (one method void move() = 0; ) NonMovableObject : GameObject - empty class...no methods or data members other than constructor and destructor(at least for now?). Later I was planning to derive a class from NonMovableObject, like Tileset : NonMovableObject. I was just wondering if "empty" abstract classes or just empty classes are often used...I notice that the way I'm doing this, I'm just creating the class NonMovableObject just for sake of categorization. I know I'm overthinking things just to make a breakout clone, but my focus is less on the game and more on using inheritance and designing some sort of game framework.

    Read the article

  • Class design, One class in two sources

    - by Pavla
    Is it possible define methods from the same class in different "CPP" files? I have header file "myClass.h" with: class myClass { public: // methods for counting ... // methods for other ... }; I would like to define "methods for counting" in one CPP and "methods for other" in other CPP. For clarity. Both groups of methods sometime use the same attributes. Is it possible? Thanks :).

    Read the article

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