Search Results

Search found 320 results on 13 pages for 'polymorphism'.

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

  • What is Polymorphism?

    - by SAMIR BHOGAYTA
    * Polymorphism is one of the primary characteristics (concept) of object-oriented programming. * Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details. * Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form. * Polymorphism is the ability to process objects differently depending on their data types. * Polymorphism is the ability to redefine methods for derived classes. Types of Polymorphism * Compile time Polymorphism * Run time Polymorphism Compile time Polymorphism * Compile time Polymorphism also known as method overloading * Method overloading means having two or more methods with the same name but with different signatures Example of Compile time polymorphism public class Calculations { public int add(int x, int y) { return x+y; } public int add(int x, int y, int z) { return x+y+z; } } Run time Polymorphism * Run time Polymorphism also known as method overriding * Method overriding means having two or more methods with the same name , same signature but with different implementation Example of Run time Polymorphism class Circle { public int radius = 0; public double getArea() { return 3.14 * radius * radius } } class Sphere { public double getArea() { return 4 * 3.14 * radius * radius } }

    Read the article

  • Is duck typing a subset of polymorphism

    - by Raynos
    From Polymorphism on WIkipedia In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. From duck typing on Wikipedia In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds. From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface. So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface. (Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct) What is the correct relationship between ducktyping and polymorphism ? If a language can duck type, does it mean it can do polymorphism ?

    Read the article

  • how to follow python polymorphism standards with math functions

    - by krishnab
    So I am reading up on python in Mark Lutz's wonderful LEARNING PYTHON book. Mark makes a big deal about how part of the python development philosophy is polymorphism and that functions and code should rely on polymorphism and not do much type checking. However, I do a lot of math type programming and so the idea of polymorphism does not really seem to apply--I don't want to try and run a regression on a string or something. So I was wondering if there is something I am missing here. What are the applications of polymorphism when I am writing functions for math--or is type checking philosophically okay in this case.

    Read the article

  • Abstract Factory Method and Polymorphism

    - by Scotty C.
    Being a PHP programmer for the last couple of years, I'm just starting to get into advanced programming styles and using polymorphic patterns. I was watching a video on polymorphism the other day, and the guy giving the lecture said that if at all possible, you should get rid of if statements in your code, and that a switch is almost always a sign that polymorphism is needed. At this point I was quite inspired and immediately went off to try out these new concepts, so I decided to make a small caching module using a factory method. Of course the very first thing I have to do is create a switch to decide what file encoding to choose. DANG! class Main { public static function methodA($parameter='') { switch ($parameter) { case 'a': $object = new \name\space\object1(); break; case 'b': $object = new \name\space\object2(); break; case 'c': $object = new \name\space\object3(); break; default: $object = new \name\space\object1(); } return (sekretInterface $object); } } At this point I'm not really sure what to do. As far as I can tell, I either have to use a different pattern and have separate methods for each object instance, or accept that a switch is necessary to "switch" between them. What do you guys think?

    Read the article

  • Reasons behind polymorphism related behaviour in java

    - by Shades88
    I read this code somewhere class Foo { public int a; public Foo() { a = 3; } public void addFive() { a += 5; } public int getA() { System.out.println("we are here in base class!"); return a; } } public class Polymorphism extends Foo{ public int a; public Poylmorphism() { a = 5; } public void addFive() { System.out.println("we are here !" + a); a += 5; } public int getA() { System.out.println("we are here in sub class!"); return a; } public static void main(String [] main) { Foo f = new Polymorphism(); f.addFive(); System.out.println(f.getA()); // SOP 1 System.out.println(f.a); // SOP 2 } } For SOP1 we get answer 10 and for SOP2 we get answer 3. Reason for this is that you can't override variables whereas you can do so for methods. This happens because type of the reference variable is checked when a variable is accessed and type of the object is checked when a method is accessed. But I am wondering, just why is it that way? Can anyone explain me what is the reason for this behaviour

    Read the article

  • Is Polymorphism and Method Overloading is almost the same thing in C++

    - by Maxood
    In C++, there are 2 types of Polymorphism: Object Polymorphism Function Polymorphism Function polymorphism is exactly the same thing as method or function overloading i.e. We use the same method names with different parameters and return types. Now the question is why do we have this fancy name Polymorphism in OOP? What distinctly distinguishes polymorphism from method overloading? Can someone explain with a scenario. Thanks

    Read the article

  • Switch vs Polymorphism when dealing with model and view

    - by Raphael Oliveira
    I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So in that view controller, each item should go to a different screen of the application and pass some data when the user select one of them. The two alternatives that comes to my mind are (please ignore the syntax, it is not a specific language) 1) switch (I know that sucks) //inside the view controller void onClickItem(int index) { A a = items.get(index); switch(a.type) { case b: B b = (B)a; go to screen X; x.v1 = b.v1; // fill X with b data x.v2 = b.v2; case c: go to screen Y; etc... } } 2) polymorphism //inside the view controller void onClickItem(int index) { A a = items.get(index); Screen s = new (a.getDestinationScreen()); //ignore the syntax s.v1 = a.v1; // fill s with information about A s.v2 = a.v2; show(s); } //inside B Class getDestinationScreen(void) { return Class(X); } //inside C Class getDestinationScreen(void) { return Class(Y); } My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff. Or should they in that case?

    Read the article

  • Problem creating levels using inherited classes/polymorphism

    - by Adam
    I'm trying to write my level classes by having a base class that each level class inherits from...The base class uses pure virtual functions. My base class is only going to be used as a vector that'll have the inherited level classes pushed onto it...This is what my code looks like at the moment, I've tried various things and get the same result (segmentation fault). //level.h class Level { protected: Mix_Music *music; SDL_Surface *background; SDL_Surface *background2; vector<Enemy> enemy; bool loaded; int time; public: Level(); virtual ~Level(); int bgX, bgY; int bg2X, bg2Y; int width, height; virtual void load(); virtual void unload(); virtual void update(); virtual void draw(); }; //level.cpp Level::Level() { bgX = 0; bgY = 0; bg2X = 0; bg2Y = 0; width = 2048; height = 480; loaded = false; time = 0; } Level::~Level() { } //virtual functions are empty... I'm not sure exactly what I'm supposed to include in the inherited class structure, but this is what I have at the moment... //level1.h class Level1: public Level { public: Level1(); ~Level1(); void load(); void unload(); void update(); void draw(); }; //level1.cpp Level1::Level1() { } Level1::~Level1() { enemy.clear(); Mix_FreeMusic(music); SDL_FreeSurface(background); SDL_FreeSurface(background2); music = NULL; background = NULL; background2 = NULL; Mix_CloseAudio(); } void Level1::load() { music = Mix_LoadMUS("music/song1.xm"); background = loadImage("image/background.png"); background2 = loadImage("image/background2.png"); Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096); Mix_PlayMusic(music, -1); } void Level1::unload() { } //functions have level-specific code in them... Right now for testing purposes, I just have the main loop call Level1 level1; and use the functions, but when I run the game I get a segmentation fault. This is the first time I've tried writing inherited classes, so I know I'm doing something wrong, but I can't seem to figure out what exactly.

    Read the article

  • Can the Abstract Factory pattern be considered as a case of polymorphism?

    - by rogcg
    I was looking for a pattern/solution that allows me call a method as a runtime exception in a group of different methods without using Reflection. I've recently become aware of the Abstract Factory Pattern. To me, it looks so much like polymorphism, and I thought it could be a case of polymorphism but without the super class WidgetFactory, as you can see in the example of the link above. Am I correct in this assumption?

    Read the article

  • Where did the "Polymorphism" word come from?

    - by Alon
    I've always wondered where did the word "Polymorphism" word come from. I know what is polymorphism and I use it of course, but I just don't understand why this technique called polymorphism. Note that I'm not a native English speaker, and I will thank you if you'll use simple English in your answers. Thank you.

    Read the article

  • Is this an example of polymorphism?

    - by computer-science-student
    I'm working on a homework assignment (a project), for which one criterion is that I must make use of polymorphism in a way which noticeably improves the overall quality or functionality of my code. I made a Hash Table which looks like this: public class HashTable<E extends Hashable>{ ... } where Hashable is an interface I made that has a hash() function. I know that using generics this way improves the quality of my code, since now HashTable can work with pretty much any type I want (instead of just ints or Strings for example). But I'm not sure if it demonstrates polymorphism. I think it does, because E can be any type that implements Hashable. In other words HashTable is a class which can work with (practically) any type. But I'm not quite sure - is that polymorphism? Perhaps can I get some clarification as to what exactly polymorphism is? Thanks in advance!

    Read the article

  • Polymorphism, Autoboxing, and Implicit Conversions

    - by dbyrne
    Would you consider autoboxing in Java to be a form of polymorphism? Put another way, do you think autoboxing extends the polymorphic capabilities of Java? What about implicit conversions in Scala? My opinion is that they are both examples of polymorphism. Both features allow values of different data types to be handled in a uniform manner. My colleague disagrees with me. Who is right?

    Read the article

  • Smart pointers and polymorphism

    - by qwerty
    hello. I implemented reference counting pointers (called SP in the example) and im having problems with polymorphism which i think i shouldn't have. In the following code: SP<BaseClass> foo() { // Some logic... SP<DerivedClass> retPtr = new DerivedClass(); return retPtr; } DerivedClass inherits from BaseClass. With normal pointers this should have worked, but with the smart pointers it says "cannot convert from 'SP<T>' to 'const SP<T>&" and i think it refers to the copy constructor of the smart pointer. How to i allow this kind of polymorphism with reference counting pointer? I'd appreciate code samples cause obviously im doing something wrong here if im having this problem. Thanks! :) [p.s., plz don't tell me to use standart liberary with smart pointers cuz that's impossible at this moment.]

    Read the article

  • How does polymorphism work in Python?

    - by froadie
    I'm new to Python... and coming from a mostly Java background, if that accounts for anything. I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code: class animal(object): "empty animal class" class dog(animal): "empty dog class" myDog = dog() print myDog.__class__ is animal print myDog.__class__ is dog From the polymorphism I'm used to (e.g. java's instanceof), I would expect both of these statements to print true, as an instance of dog is an animal and also is a dog. But my output is: False True What am I missing?

    Read the article

  • Is dependency injection by hand a better alternative to composition and polymorphism?

    - by Drake Clarris
    First, I'm an entry level programmer; In fact, I'm finishing an A.S. degree with a final capstone project over the summer. In my new job, when there isn't some project for me to do (they're waiting to fill the team with more new hires), I've been given books to read and learn from while I wait - some textbooks, others not so much (like Code Complete). After going through these books, I've turned to the internet to learn as much as possible, and started learning about SOLID and DI (we talked some about Liskov's substitution principle, but not much else SOLID ideas). So as I've learned, I sat down to do to learn better, and began writing some code to utilize DI by hand (there are no DI frameworks on the development computers). Thing is, as I do it, I notice it feels familiar... and it seems like it is very much like work I've done in the past using composition of abstract classes using polymorphism. Am I missing a bigger picture here? Is there something about DI (at least by hand) that goes beyond that? I understand the possibility of having configurations not in code of some DI frameworks having some great benefits as far as changing things without having to recompile, but when doing it by hand, I'm not sure if it's any different than stated above... Some insight into this would be very helpful!

    Read the article

  • How to Elegantly convert switch+enum with polymorphism

    - by Kyle
    I'm trying to replace simple enums with type classes.. that is, one class derived from a base for each type. So for example instead of: enum E_BASE { EB_ALPHA, EB_BRAVO }; E_BASE message = someMessage(); switch (message) { case EB_ALPHA: applyAlpha(); case EB_BRAVO: applyBravo(); } I want to do this: Base* message = someMessage(); message->apply(this); // use polymorphism to determine what function to call. I have seen many ways to do this which all seem less elegant even then the basic switch statement. Using dyanimc_pointer_cast, inheriting from a messageHandler class that needs to be updated every time a new message is added, using a container of function pointers, all seem to defeat the purpose of making code easier to maintain by replacing switches with polymorphism. This is as close as I can get: (I use templates to avoid inheriting from an all-knowing handler interface) class Base { public: template<typename T> virtual void apply(T* sandbox) = 0; }; class Alpha : public Base { public: template<typename T> virtual void apply(T* sandbox) { sandbox->applyAlpha(); } }; class Bravo : public Base { public: template<typename T> virtual void apply(T* sandbox) { sandbox->applyBravo(); } }; class Sandbox { public: void run() { Base* alpha = new Alpha; Base* bravo = new Bravo; alpha->apply(this); bravo->apply(this); delete alpha; delete bravo; } void applyAlpha() { // cout << "Applying alpha\n"; } void applyBravo() { // cout << "Applying bravo\n"; } }; Obviously, this doesn't compile but I'm hoping it gets my problem accross.

    Read the article

  • OOP design issue: Polymorphism

    - by Graham Phillips
    I'm trying to solve a design issue using inheritance based polymorphism and dynamic binding. I have an abstract superclass and two subclasses. The superclass contains common behaviour. SubClassA and SubClassB define some different methods: SubClassA defines a method performTransform(), but SubClassB does not. So the following example 1 var v:SuperClass; 2 var b:SubClassB = new SubClassB(); 3 v = b; 4 v.performTransform(); would cause a compile error on line 4 as performTransform() is not defined in the superclass. We can get it to compile by casting... (v as SubClassA).performTransform(); however, this will cause a runtime exception to be thrown as v is actually an instance of SubClassB, which also does not define performTransform() So we can get around that by testing the type of an object before casting it: if( typeof v == SubClassA) { (cast v to SubClassA).performTransform(); } That will ensure that we only call performTransform() on v's that are instances of SubClassA. That's a pretty inelegant solution to my eyes, but at least its safe. I have used interface based polymorphism (interface meaning a type that can't be instantiated and defines the API of classes that implement it) in the past, but that also feels clunky. For the above case, if SubClassA and SubClassB implemented ISuperClass that defined performTransform, then they would both have to implement performTransform(). If SubClassB had no real need for a performTransform() you would have to implement an empty function. There must be a design pattern out there that addresses the issue.

    Read the article

  • Understanding Tcl Polymorphism

    - by Xofo
    In Tcl a variable and a procs can have the same name ... for instance I can have set container(alist) {} proc container a {puts " do something"} Um ... what other forms of polymorphism exist in tcl? ... I am looking at some code and I see stuff like this.

    Read the article

  • How to have Moose return a child class instance instead of its own class, for polymorphism

    - by alex8657
    I want to create a generic class, whose builder would not return an instance of this generic class, but an instance of a dedicated children class. As Moose does automatic object building, i do not get to understand if this something possible, and how to create a Moose class with Moose syntax and having this behaviour Eg: The user asks: $file = Repository-new(uri='sftp://blabla') .... and is returned an Repository::_Sftp instance User would use $file as if it is a Repository instance, without the need to know the real subclass (polymorphism)

    Read the article

  • Virtual functions and polymorphism

    - by ritmbo
    Suppose I have this: class A { public: virtual int hello(A a); }; class B : public A { public: int hello(B b){ bla bla }; }; So, A it's an abstract class. 1)In the class B, I'm defining a method that its suppose overrides the A class. But the parameter it's slightly different. I'm not sure about this, is this correct? Maybe because of polymorphism, this is ok but its rather confusing. 2) If I do: A a = new B;, and then a.hello(lol); if "lol" it's not of type B, then it would give compile error?, and if it's of type A from another class C (class C : public A), what would happend? I'm confused about the overriding and virtual thing.. all examples I found work with methods without parameters. Any answer, link, or whatever it's appreciated. thanks pd: sorry for my english

    Read the article

  • Questions about my program and Polymorphism

    - by Strobe_
    Ok, so basically I'm creating a program which allows the user to select a shape (triangle, square, circle) and then it takes in a int and calculates the boundary length and area. I have no problem doing this and have a program that's working perfectly. (https://gist.github.com/anonymous/c63a03c129560a7b7434 4 classes) But now I have to implement this with polymorphism concepts and I'm honestly struggling as to how to do it. I have a basic idea of what I want to do when it comes to inheritance Main | Shapes / | \ triangle circle square But I don't understand how I'm supposed to override when all the methods within the triangle/square/circle classes are unique, there are no "abstract" methods as such that I could inherit from the "Shapes" class. If somebody could make look quickly at the code I linked and suggest a way to do this it would be much appreciated. Sorry if I was bad at explaining this. Thanks.

    Read the article

  • c++ polymorphism and other function question

    - by aharont
    i have got this code: class father{ public: virtual void f() { cout<<1;} }; class son:public father{ public: void f() {cout<<2;} }; void test (father x){x.f();} int main(){ son s; test(s); } the question says: the output is '1', what is the rule about polymorphism that the programmer forgot and how can i fix it so the output would be '2'? there is another rule that the programmer forgot when he wrote the father class, and he need to add an empty function to avoid problems from other sons of the father class. what is the rule and what is the missing function? another question write the g function so the next code would run with no crashes int x=11; g(x)=22;

    Read the article

  • Subtype polymorphism and arrays

    - by user133466
    Computer[] labComputers = new Computer[10]; with public class Computer { ... void toString(){ // print computer specs } } public class Notebook extends Computer{ ... void toString(){ // print computer specs + laptop color } } each subscripted variable labComputers[i] can reference either a Computer object or a Notebook object because Notebook is a subclass of Computer. For the method call labComputers[i].toString(), polymorphism ensures that the correct toString method is called. I wonder what if we do Notebook[] labComputers = new Notebook[10]; what kind or error would I get if I reference with Computer object and a Notebook object

    Read the article

  • Classes, methods, and polymorphism in Python

    - by Morlock
    I made a module prototype for building complex timer schedules in python. The classe prototypes permit to have Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole construction or Timers and Repeat instances. The construction can be as complex as needed and needs to be flexible. Each of these three classes has a .run() method, permitting to go through the whole schedule. Whatever the Class, the .run() method either runs a timer, a repeat group for a certain number of iterations, or a schedule. Is this polymorphism-oriented approach sound or silly? What are other appropriate approaches I should consider to build such a versatile utility that permits to put all building blocks together in as complex a way as desired with simplicity? Thanks! Here is the module code: ##################### ## Importing modules from time import time, sleep ##################### ## Class definitions class Timer: """ Timer object with duration. """ def __init__(self, duration): self.duration = duration def run(self): print "Waiting for %i seconds" % self.duration wait(self.duration) chime() class Repeat: """ Repeat grouped objects for a certain number of repetitions. """ def __init__(self, objects=[], rep=1): self.rep = rep self.objects = objects def run(self): print "Repeating group for %i times" % self.rep for i in xrange(self.rep): for group in self.objects: group.run() class Schedule: """ Groups of timers and repetitions. Maybe redundant with class Repeat. """ def __init__(self, schedule=[]): self.schedule = schedule def run(self): for group in self.schedule: group.run() ######################## ## Function definitions def wait(duration): """ Wait a certain number of seconds. """ time_end = time() + float(duration) #uncoment for minutes# * 60 time_diff = time_end - time() while time_diff > 0: sleep(1) time_diff = time_end - time() def chime(): print "Ding!"

    Read the article

  • Is this an example for parametric polymorphism?

    - by mrt181
    Hi i am educating myself oop principles. I would like to know if this is a correct example of Cardellis definition of parametric polymorphism. Please enlighten me. The example is in cfml's script based syntax. <cfcomponent> <cfscript> public numeric function getlength(any arg, string type){ switch (arguments.type){ case "array": return arraylen(arguments.arg); break; case "struct": return structcount(arguments.arg); break; case "string": return len(arguments.arg); break; case "numeric": return len(arguments.arg); break; case "object": // gets the number of parent classes, substracting the railo base class return -1 + arraylen(structfindkey(getmetadata(arguments.arg),"extends","all")); break; default: // throw was added to railo as a user defined function to use it in cfscript throw("InvalidTypeArgument","The provided type argument is invalid for method getlength"); } } </cfscript> </cfcomponent>

    Read the article

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