That is a good question. . . I don't like the term compile-time polymorphism. You can use runtime binding (polymorphism) with instance methods. Static members and fields, if called, are bound to their declaring class at compile-time, but lots of people here post how much they get confused when that happens, so it is probably best to say there is no ... |
For your first question: Method over-loading and over-riding, both are form of polymophism. However, there is a difference. Over-riding exhibits Dynamic-polymorphism or run-time polymorphism. Which Method call is decided at run-time by the JVM. In method over-loading, the specific method to be called is decided at compile time. This is what basics I know. There may be more to it. |
Polymorphism is derived from the chains of inheritance in Java. Inheritance shows a relationship between two or more classes in which the parent class (also called the superclass) passes attributes and methods to the child class (also called the subclass). Example: You have three classes: Insect, Termite, and Bee; In inheritance the more broad term is always the Parent class, so ... |
thanks Rob Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) from above statement- looks ... |
|
Declare method eat() in class Animal as well. In Java, a method (or field) must be present in the reference class. Although the actual methods are Dog and Cat instances, the compiler doesn't know - all it knows is that they are Animal objects. And in your example Animal does not have the eat() method, so the compiler won't allow you ... |
class A { int x=5; } class B extends A { int x=6; } class covtest { public A getObject() { System.out.println("its A from covtest"); return new A(); } public static void main(String arg[]) { covtest t = new subcovtest(); System.out.println(t.getObject().x); // * } } class subcovtest extends covtest { public B getObject() { System.out.println("its B from subcovtest"); return new B(); ... |
|
well suppose you had a superclass and several subclasses. Polymorphism allows you to have declare variables of the type of the single superclass that can contain references to objects of any of the subclasses. then you could reference (call) a method using the superclass variable, yet the actual method being called would depend on the type of the subclass object being ... |
|
OK, I tried running it, and I get 10/20 too, no warnings (1.6.0_15 on Mac OS X). Hmmm. I suppose the Eclipse warning is the key to what's going on. Because the Top foo() method is hidden from Bottom, the like-named method does not override it; Top.foo() and Bottom.foo() are entirely unrelated methods. If Top.foo() were private, exactly the same thing ... |
Can anyone help me by indicating what steps are involved when understanding tricky polymorphism questions.. They always get me stumped no matter what I do the IS-A test against. E.g.. class A{} class B extends A{} class C extends A{} final class D extends B{} public void doSomething() { A a = new B(); B b = new D(); C c ... |
|
|
Hi! I just registered on the forums but I have been reading for a while. I have a problem with a project we're working on. It's a 2D platformer game and I have programmed the physics and collision handling. The problem is, I want to get a specific response out of a collision depending on the actual types of the two ... |
The output of below shown code is: test Base constructor der Derived constructor der Baseprintsec der class base { public void printMe() { System.out.println("Base"); } public base() { System.out.println("Base constructor"); printMe(); // Please explain this } public void printMesec() { System.out.println("Baseprintsec"); printMe(); } } class Derived extends base { public void printMe() { System.out.println("der"); } public Derived() { System.out.println("Derived constructor"); printMe(); ... |
abstract class Employee { private String name; private String address; protected double salary; public Employee(String name, String address, double salary) { this.name = name; this.address = address; this.salary = salary; } public double raise(); // abstract method } I want to write the code about polymorphism. // secretaries class Secretary extends Employee { Secretary(String name, String address,double salary) { super(name, address, ... |
Hello! I would like to ask you a question.. Should you be asked "why are oo concepts such as polymorphis, abstraction etc so important? Could you please motivate your answer with a real world example (avoid classical examples like Shapes and Animals, please)?", how would you answer? Can you please point me to some online resources about this please? Thanks a ... |
In regards to http://www.javaranch.com/campfire/StoryPoly.jsp/teaching polymorphism to dogs, I wish I had that dog's smarts . . . So I can't get past the third line before a big question mark forms over my head, clouding the rest of the article . . . Ok, so I don't understand why this: Dog d = new Dog(); is not simply this d = ... |
|
..construct may not be the right word, but take this example: class A { } class B extends A { } Ok I understand this, and how polymorphism work. but the following line: A a = new B(); Why would someone ever instantiate the B with A? Is there a real world example that could used to explain where this could ... |
|
|
you can use following code void AnimalTest(Animal animal) { animal.eat(); //no problem with that, all animals eat if(animal instanceof Cat){ // it check if the animal reference variable have cat as object or animal if cat then it allowes it to go in and the you can invoke sing menthod on cat cat c = (cat)animal; c.sing() } } |
Hello my name is Brian. I am learning polymorphism at the moment but still unclear of the concept. I'm having some problems figuring out what would be that advantage of using a superclass reference pointing to a subclass. I took this snippet from the Sun Certified Java Programmer book. The part I dont understand is why do we need to do: ... |
class Employee { public void getSal(String...args) { System.out.print("Employee getting sal..."); } public void setSal() { System.out.print("Employee Setting sal..."); } } class Engineer extends Employee { public void getSal(String a) { System.out.println("Enginner Getting sal..."); } public void setSal() { System.out.println("Enginner Setting sal..."); } public static void main(String args[]) { Employee a=new Engineer(); Engineer b=(Engineer)a; a.getSal("test"); } } |
I am trying to find an example that includes both overridden methods and subclass-specific methods and I can't seem to find any. It seems like in the past I've used a base class to take advantage of polymorphism, and have then wanted to use the derived instances. Is this something that never happens or should never happen? Here is an example: ... |
public class Main { public static void main(String[] args) { Shape c = Circle(); c.draw(); } } public class Shape { public static void draw(){ System.out.println("draw this shape"); } public void erase(){ System.out.println("erase the shape"); } public static void main (String[] args) { System.out.println("this is a shape"); } } public class Circle extends Shape { public static void draw() { System.out.println("draw ... |
|
Polymorphism is the deebil (Java in General forum at JavaRanch) A friendly place for programming greenhorns! Register / Login Java Forums Java Java in General Polymorphism is the deebil Post by: Hansjoachim Vonhortenschiem, Greenhorn on Mar 03, 2011 20:35:02 Sorry to post redundate info requests, but I've just finished the nights reading, (no, I'm not in school.. I graduated ... |
Hi, all. In some interviews, the interviewer asks me about run time polymorphism and compile time polymorphism. I know about run time polymorphism. But I never knew compile time polymorphism. When I searched online it seems that people refer to overloading as compile time polymorphism. But many books authoritatively say that overloading has nothing to do with polymorphism and I can ... |
Hi, We know method overloading is the compile time ploymorphism. Means compiler is able to match the name of the methods at the compile time only. But how can we prove this with any example that this is happening in compile time only.. any practical example instead of the theoretical concept. can we prove this practically with some exmaple. Regards, Prabhat ... |
Hey guys, so am halfway through Head First into Java and ran into this wallbanger of a confusion. Lets say.. abstract class Animals { void makeNoise() { } } class Dog extends Animals { void makeNoise() { System.out.println("Woof! Woof!"); } } //Now lets assume we've added a dog object and some other animals into two arrays of Animals and Object types... ... |
I know for the vets this has been discussed to death, but for the newer people I wanted to share. I set out yesterday to replace an if statement based on a boolean flag; I was convinced there was a better way.. And there was, but it took some mind twisting to get there. I learned a lot of really really ... |
public class GameShape{ public void displayShape(){} } public class PlayerPiece extends GameShape{ public void movePiece(){} } public class TilePiece extends GameShape{ public void getAdjacent(){} } public class DicePiece extends GameShape{ public void rotatePiece(){} } There is a class called Animatable as below, public class Animatable{ public void animate(){} } I need animate method in TilePiece & DicePiece class. But java has ... |
Background: I have an object that is populated from a web page. Based on what the user sets, I need to send a request to a web service. The request uses axis2 generated code, and takes a base class object as a parameter. I have no control over the base class or sub classes I take one of the input parameters ... |
you are creating the dog object and giving it to a animal reference. Such situation might occur when you create List Object. List is a interface , so you create a Object for arrayList or any of the classes that implements List and referenc it to List . List l = new ArrayList(); |
In Java it is necessary to explicitly down cast, particularly when using utilities that retrieve to Object references, for example, and code designed to benefit from polymorphism. However, explicit down cast and code using instanceof are often responsible bugs and perpetual maintenance problems. Does anyone know if there is an effort to eliminate the need for explicit down cast in core ... |
I'm confused with this statement. My wild theories that you don't need to know right now: The switch statement is certainly better than a long series of "if" statements, but I have found that whenever I start to implement a switch statement, I can almost always find a better program design - usually by using an array or making a method ... |
|
|
1. Look at the first constructor? Follow its logic, does it go anywhere? 5. Reread the information on static variables(Understanding Instance and Class Members (The Java Tutorials > Learning the Java Language > Classes and Objects)) but basically static variables go across instances, meaning calls to it from any instance will update it for all instances. The final modifier is used ... |
|
Hey hey, For university I am reading through the book "Absolut Java" and I am reading through the polymorphism chapter and have hit a bit of snag. It's just a few definitions which confuse me.. Whats the difference between a method definition and a method invocation? I assumed a method definition was... public int getInt(){ return intValue; } I thought that ... |
Hi, I have gone through the video explaining Polymorphism 3 times, and i'm still confused. According to the video Polymorphism makes most sense when its used in/as a "Polymorphic array"... which again does not make a whole lot of sense. Ok, the array can hold objects of different classes... so what? My question to you guys who program a lot, do ... |
|
ok so would this be an example of dynamic-binding, and if so could you explain why? public class MoveShapes5_1 { public static void main(String args[]) { public Moveable s[ ]; s = CreateShapes5_1(6); for(int i=0; i |
According to my knowledge,compiler converts source code in one languague to source code in another languague. But in a book i read during compile time polymorphism the compiler links all the methods with the appropriate arguments(method overloading) at compile time. Does it mean compiler checks whether the arguments match with the signature of the methods ?? Or it will link the ... |
i have read during compile time polymorphism, the compiler links the methods with the argument list(overloading). But compilers actually convert the source code in one languague to another languague. So does it mean compiler just checks whether the methods are provided with appropriate arguments or not inorder to report error or does it do more ? Sorry if my question is ... |
i have a doubt regarding polymorphism Yesterday i studied an article polymorphism. A mentioned in article :: The key point in polymorphism is the separation of interface from its implementation.Say for example List name=new ArrayList(); But my doubt here is if the reference variable is of type List then we can access only the methods of Interface List not the methods ... |
Hi Guys....I have an interview and I am preparing for it with the help of google.....my interview is on core java...i.e. OOPs, Collections, Datastructures, threads and graphics....first of all can I have any good interview preparing articles and secondly I was searching for Polymorphism and I found these two terms....Single Polymorphism and Multiple Polymorphism and after reading from diff websites now ... |
|
If you want to return an array of FileSubclass objects, then you first have to create the array, then you have to create one FileSubclass object for each position of the array. You can't delegate that to the superclass because it doesn't know how to create a FileSubclass object. I assume you must have a way of converting a File object ... |
Fine .. But still i have got another doubt.. We all are writing our onw java code which has got a main method with String array as an argument. We are not supposed to change the signature of that method. That means , we are implementing an existing method,which is declared but not defined, in our own ways.(Hope every one are ... |
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming explains it beautifully Basically, if Class A has a method called doStuff() , and Classes B and C extend Class A, then B and C are guaranteed to have the doStuff() method. So if your main class creates both a B object and a C object, it can pick one at random and call doStuff() without knowing which one is ... |
Aren't you rather reinventing the wheel here? Shape has a method getBounds wich returns a Rectangle, and repaint has a form that accepts a Rectangle argument. If you need to increment the height and width of the bounds rectangle by OFFSET,you can easliy do that without having to add a new Interface. db |
I'm having trouble with writing these 2 methods: The public method Object get(Object key) which calls getEntry() and returns the value of the Entry with the specified Key. This method is inherited by the derived classes and calls getEntry() polymorphicly. The public method Object put(Object key, Object newValue) which calls getEntry() to see if the entry already exists. If it does ... |
Polymorphism can essentially be described (for these purposes) this way An Apple is a Fruit, and an Orange is a Fruit, but an Apple is not an Orange. So if you want to have a collection of Fruit, you want Apple and Orange to both be subclasses of Fruit. Likewise, a Rectangle is a kind of Shape, and a Circle is ... |
|
|
|
Because the language spec says it's legal, an the reason it makes sense and it's easy to make it work is because of the is-a relationship. Parent p means that p is a reference to an object that IS-A Parent, and that anything you can do with a Parent, you can do with whatever object that p reference points to, because ... |
I don't understand why you have all these other classes. Are they part of the requirements? All you need is a Random object to generate your numbers. If you place your operators in an array and use the same Random object to generate numbers from 0-3 inclusive then you can access the operator at that position in the array. Once you ... |
|
Only if |type of obj| <: |Sheep| or |Sheep| is <: |type of obj| or a compile time error occurs. Furthermore if there is a supertype X of the type of obj and a supertype Y of Sheep such that X and Y are provenly two distinct parametrized types and the erasure of X and Y is the same, a compile-time ... |
I've been reading about factory patterns lately. While doing so I've been wondering about the following: Is the whole idea of polymorphism that objects have the same method-declarations but different implementations? If so, is there ever a situation in which one would allow 'extra' methods in a subclass? There's a saying: "code to the interface, not to the implementation". If you ... |
What do we really achieve, using polymorphism class super { void get(); } class sub { void get(); } super a = new super() sub b = new sub() why cant we call whichever implementation of get() we want using that class' object itself, instead of using: super a = new super() sub b = new sub() super c; c = ... |
|
hi, The following is the Static and dynamic polymorphism.See the below program and execute it you will understand what is static and dynamic polymorphism. public interface Animal { public void walk(); public void sleep(); } Now take two classes 1)cat 2)Rat public class Cat implements Animal { public void walk() { System.out.println("cat is walking"); } public void sleep() { System.out.println("cat is ... |
|
I am not that comfortable with Java's enum types, so please allow me to ask the following: I am trying to model a restaraunt. The "Restaraunt" class will be abstract. Concrete classes like "Wendys", "BurgerKing", etc. will extend it. One abstract method in the Restaraunt class needs to be: getMenu(). And, the "getMenu()" method returns an enumeration of the items on ... |
Greetings to everyone. I would like to ask for a help about polymorphism. In my simple understanding polymorphism is an ability of a subclass to "pretend" as a superclass. In this example demonstrates polymorphism but unfortunately I can't understand why it is being applied here in this example. Honestly It doesn't makes sense to me. Please help me. package testing; public ... |
|
NewInJava wrote: The problem, is that I don't know how to get the toString() from my GradedActivity to print out from my PassFailExam. That sentence doesn't quite make sense. If you have a GradedActivity object and you want it's string representation, you can call its toString method. The same applies for a PassFailExam object, or any object. In some circumstances, toString ... |
Hi, By type of account I mean all the subclasses that extend form Account. Account is abstract. Types (subclasses) of Accounts are: Savings, LineOfCredit, OverdaftProtection and Investment. But I will add a lot more account subclasses of Account later, and I do not want to modify the code for this method to check for every subclass of Account. I wanted to ... |
|
Hi All, I'm hoping you might be able to help me with a small problem. Let's say I have two classes: a User class and a UserWithMiddleName class that extends User. UserWithMiddleName just has an additional public property for the user's middle name. Basically I want to take a User object and then transform it to a UserWithMiddleName object so that ... |
|
|
|
Bloody hell, do I love programming. Where else, at the age of 52, could I find something that challenges me every day? No doubt many of you have come across something like this in your work, but it's new to me, and I wondered if it's an established design pattern (and, God knows, it ain't nothin' if it ain't a "pattern"). ... |
|
The compiler always links a method invocation to the best-fitting method. When you invoke a.foo, the compiler thinks: "a is in instance of Alpha. this may or may not be an instance of Beta, thus it may or may not have method foo(String). Let's use a method which we can be sure a has at run-time - and is the best-fitting ... |
You are right from programming point of view.. but what is the answer from compiler point of view what can go wrong. public class B { public int filed =10; public int method(){ return filed; } } public class D extends B { public int field =20; public int method(){ return field; } public static void main(String str[]){ B b = ... |
becky3 wrote: why do i have no access from "Test1" to the member variable "value1" which is initialized in class "Test2" although i'm calling the constructor "Test2()"? Because the type of t3 is reference to Test3, and Test3 does not have a value1 variable. The compiler doesn't know that at runtime that reference is going to point to a subclass of ... |
|
|
|
Hi all, I know that i should know this, but i don't! I have coded a class with lets say 2 methods, one public and one protected. When you call the public method it in turn makes a call to the protected method. I have now sub-classed this and over-ridden the protected method - my aim is that when someone calls ... |
class Shape { protected Color color; protected int x, y; Shape (Color c, int xPosition, int yPosition) { color = c; x = xPosition; y = yPosition; } // constructor public void drawShape (Graphics g) { g.setColor (color); g.drawString ("Shape", x, y); } // method drawShape } // class Shape class Circle extends Shape { private int radius; Circle (Color c, ... |
|
|
use either myobject.getClass().equals(my.Class) and compare it to some Class object you have, or use (myobject instanceof my.Class) which returns true if myobject is an instance of my.Class. Note that there is a subtelty here: myObject instanceof my.Class will return true if myObject is an instance of my.Class or any of its subclasses, while myobject.getClass().equals(my.Class) will return true only if myObject is ... |
I have 4 classes: an abstract class Employee and 3 sub classes: TempEmployee,SalesEmployee,RegularEmployee. I also have a class with an array Employees. I want to write in that class a method addEmployee which recieves an object (one of the 3 employees) and adds it to the array. I also want to avoid aliasing so I want to use the copy constructor ... |
|
|
The pre-compiler asks me if I want him to create "getCountersBox2()" in "CountersBoxesCabinet". No, indeed ! I just want "getCountersBox2()" to return the value of the "counter2" property included in the inherited "CounterBox_2C" object ! Attached file "Counter2NotFound.bmp" illustrates a screen capture of NetBeans IDE at that time. See here my 6 classes, ready for compilation. Main.java package strugglingpoint; public ... |
robi, If subclass1 and subclass2 require varying functionality then "the OO doctrine" says that that "varying functionality" should be implemented in subclass1 and subclass2, with a common interface defined by the superclass (or an interface). This means that the "user" of your class heirarchy (your "another" class) just calls superClass.whatever(), and the appropriate definition of whatever() will be executed. It's hard ... |
|
question: a few years back I wrote a server that used polymorphism via inheritance. It was something like this: base class: class Player { .. public void takeTurn() { .. } } the child classes: class Human extends Player { .. public void takeTurn() { .. } } class Robot extends Player { .. public void takeTurn() { .. } } ... |
What is the best way of finding out the runtime class of an object? More specifically lets say there is a method that takes an Abstract Class as a parameter but the method should behave differently depending on which subclass of the abstract class is actually passed to it at runtime. How could the method know which subclass has actually been ... |