I have confusion regarding Method Overriding in java.
From it's definition it says :
In any object-oriented programming language, Overriding is a feature
that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
super-classes or parent classes.
Now, below is one example regarding it :
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent {
#Override
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
I have doubt at this line :
Parent obj2 = new Child();
I can do the same thing using :
Child obj2 = new Child();
then why I need to declare it with the name Parent class?
What it's purpose?
Like you said, you don't need to declare subclass objects as their parent class, but there are other cases where this may be important, such as when you are trying to make things abstract.
What is Abstraction?
Abstraction is removing everything but the most essential. A really good example you probably already use a ton is Lists.
Whether you are using an ArrayList, a LinkedList, or any other type of Java list, you know that there are certain properties that you can always count on being there, like getting the size of the list, getting a certain element at a certain point, etc.
This DRAMATICALLY simplifies the use of these, and you can interchange them depending on your application. This is all because they are a subclass of List, in which these methods come from.
The ways that an ArrayList, and a LinkedList get and set data are different, but from the perspective of you, the user of these sub classes, the implementation is the same, you just use the classes that were overridden. It's super convenient, because you don't need to know a thing about coding, try whatever you're trying to do with a linkedlist, then with an arraylist, and see whats faster.
What's your part in this?
In the example you gave, it is very simple, and doesn't matter, but say you were making a class that sorted lists in a particular, fun, amazing way.
If you declared everything as just a List, users of your class could pass in both ArrayLists, and LinkedLists, depending on what they were doing, and both would work. So, to be a good programmer, try to keep everything as abstract as possible. It's a good rule to learn early on.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
Related
I've got a task to do polymorphism but I am not entirely sure I understand the concept as per testimony of my teacher.
According to web definitions and examples, this by all means is polymorphism, but they say it is not. Can I please get confirmation?
OversizedParcel.java
public class OversizedParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do theese
//and those
}
public void resolve(LegalUser user) {
//do different thing
//and a completely different thing
}
}
IllegalParcel.java
public class IllegalParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do this
//do that
}
public void resolve(LegalUser user) {
//do a thing
//do a different thing
}
}
(hypothetical class)
public class Main{
private User user; //loaded user
private List<ParcelType> parcels; //assume this contains the loaded parcels already
public static void main(String[] args){
for(ParcelType type : parcels) type.resolve(user);
}
}
Polymorphism can be defined as -
it is the ability of an object to take on many forms
. The most common example of polymorphism could be-
when a parent class reference is used to refer to a child class
object.
So as per your question, in most simplistic way polymorphism can be defined as
ParcelType oversizedparcel = new oversizedParcel();
ParcelType illegalparcel = new illegalParcel();
Here ParcelType can be a oversizedParcel or illegalparcel
So if your understanding is as per my answer, then indeed it is an example of polymorphism.
I'd like to offer a dissenting opinion from what appears to be majority here. Keep in mind that "Polymorphism" is a fairly flexible term, and that what is written here does not necessitate 100% universal truth. This is simply something to aid the balance of thought.
No, what you have written is not polymorphism. This is due to the fact that they instantiate different unrelated objects that simply implement the same interface.
Traditionally, Polymorphism occurs when you have a child object that overrides a parent object's implementation of a method. Hence, there is "multiple forms" of a method that exist at the same time at different levels of the object's vertical hierarchy.
However, interfaces are merely an agreed-upon contract of inputs and outputs that standardize interactions. They don't by themselves hold an instance of the code (we shall exclude default interface methods for the sake of this conversation). Because of this, there is no "Re-definition" of the interface within an object. the same object tree does not instantiate multiple versions of the interface (unless it is through the traditional view of polymorphism).
Even if a method required two arguments of interface ParcelType, it does not necessarily mean polymorphism, it simply means that the method is asking for two 'boxes' of a particular shape and size. These boxes are empty until they are passed into the method as two distinctly different objects that are referenced separately (And not the same method object being overridden by a child object, for example)
Different objects can take advantage of the interface contract, and in a way you can say that it is "Horizontal Polymorphism", but I think this is taking away from the intention of what polymorphism means in the context of Java.
According to the W3School definition, it is indeed polymorphism. Anyway, if your teachers said it is not, they may have been expecting you to do something else.
Polymorphism is, to go further than just an example, an entire concept meaning that you can do entirely different things by using "the same things", or more exactly "things named the same".
Have a look on the Wikipedia definition, which is more complete than any language-specific one, to have a wider view on it.
Polymorphism is having the same thing in different forms. So, Yes this is polymorphism.
I assume that resolve is defined in ParcelType interface. Then the type.resolve calls in for(ParcelType type : parcels) type.resolve(user) are dispatched polymorphically on ParcelType
I was assigned to a project, and it is my job to implement a feature to the already existing system. This functionality needs to be added to two seperate classes. Both of these classes extend the same super class, but it does not make sense to add the feature to this superclass. What is the best way I can implement the same functionality into these two seperate classes without too much code duplication. The simple way would be implementing this functionality into a static class and then using the static methods in the two classes that need this extra functionality, but that sort of seems like bad design.
Is there any sort of design I can use to implement something like this, or is me running into this problem just showing a larger issue in the hierarchy that should be fixed rather than try to work on top of it?
Java does not have stand-alone "static" classes, so that's a non-starter since it's not even possible. As for use of static methods, that's fine if you're talking about stateless utility methods.
Myself, I guess I'd solve this with composition and interfaces:
Create an interface for the functionality that I desire
Create concrete instance(s) of this interface
Give the two classes fields of the interface
Plus getter and setter methods for the interface.
If the classes had to have the new behaviors themselves, then have them implement the interface, and then have these classes obtain the behaviors by "indirection" by calling the methods of the contained object in the interface methods.
I'm sorry that this answer is somewhat vague and overly general. If you need more specific advice from me or from anyone else here, then consider telling us more of the specifics of your problem.
Determine what common features of these two classes the new functionality relies on. Then, extract those features to an interface, modify the two classes to implement that interface, and put the new functionality code in its own class (or possibly a static method somewhere, e.g. NewFeature.doTheThing(NewFeaturable toWhat)) and make it operate on those interfaces.
If the existing classes have to obtain information from / call methods related to the "new feature", then give them a NewFeature field that is an instance of the new feature class and have them interact with that object. Pseudo-ish code:
interface NewFeaturable {
int getRelevantInfo ();
}
class NewFeature {
final NewFeaturable object;
NewFeature (NewFeaturable object) { this.object = object; }
void doSomething () { int x = object.getRelevantInfo(); ... }
}
class ExistingClass extends Base implements NewFeaturable {
final NewFeature feature;
ExistingClass () { ...; feature = new NewFeature(this); }
#Override int getRelevantInfo () { ... }
void doSomethingNew () { feature.doSomething(); }
}
Be wary of new NewFeature(this) there, as subclasses of ExistingClass will not be fully constructed when it is called. If it's an issue, consider deferring initialization of feature until it is needed.
A lot of the specifics depend on your exact situation, but hopefully you get the general idea.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
When I started to look for the benefits of polymorphism, I found with this question here. But here I was unable to find my answer. Let me tell what I want to find. Here I have some classes:
class CoolingMachines{
public void startMachine(){
//No implementationion
}
public void stopMachine(){
//No implementationion
}
}
class Refrigerator extends CoolingMachines{
public void startMachine(){
System.out.println("Refrigerator Starts");
}
public void stopMachine(){
System.out.println("Refrigerator Stop");
}
public void trip(){
System.out.println("Refrigerator Trip");
}
}
class AirConditioner extends CoolingMachines{
public void startMachine(){
System.out.println("AC Starts");
}
public void stopMachine(){
System.out.println("AC Stop");
}
}
public class PolymorphismDemo {
CoolingMachines cm = new Refrigerator();
Refrigerator rf = new Refrigerator();
}
Now here I created two objects in the Demo class and are references of Refrigerator. I have completely understood that from the rf object I am able to call the trip() method of Refrigerator, but that method will be hidden for the cm object. Now my question is why should I use polymorphism or why should I use
CoolingMachines cm = new Refrigerator();
when I am OK with
Refrigerator rf = new Refrigerator();
Is polymorphic object's efficiency is good or light in weight? What is the basic purpose and difference between both of these objects? Is there any difference between cm.start(); and rf.start()?
It is useful when you handle lists...
A short example:
List<CoolingMachines> coolingMachines = ... // a list of CoolingMachines
for (CoolingMachine current : coolingMachines) {
current.start();
}
Or when you want to allow a method to work with any subclass of CoolingMachines
In cases where you're really okay with knowing the concrete class, there's no benefit. However, in many cases you want to be able to write code which only knows about the base class or interface.
For example, look at Iterables in Guava - that's a lot of methods which (mostly) don't care what implementation of Iterable is being used. Would you really want all that code separately for every implementation?
Where you can code to an abstract base class or an interface, you allow yourself to later use other implementations which share the same public API, but may have different implementations. Even if you only want a single production implementation, you may well want alternative implementations for testing. (The extent to which this applies very much depends on the class in question.)
Because later if you want to use AirConditioner instead of Refrigerator for cooling, then only code you need to change is CoolingMachines cm = new AirConditioner();
The reason that you want to use
CoolingMachines cm = new Refrigerator();
is that you can later easily use a different CoolingMachines. You only need to change that one line of code and the rest of the code will still work (as it will only use methods of CoolingMachines, which is more general than a specific machine, such as a Refrigerator).
So for a particular instance of Refrigerator, the calls cm.start(); and rf.start() work the same way but cm might also be a different CoolingMachines object. And that object could have a different implementation of start().
First answer:
Use polymorphism for method overridding and method overloading. Other class methods used in different class then two options: first method inherited, second method over written. Here extend interface: use them, or implemention method: logic write them. Polymorphism used for method, class inheritance.
Second answer:
Is there any difference between cm.start(); and rf.start();?
Yes, both are objects that are completely different with respect to each other. Do not create interface objects because Java doesn`t support interface objects. First object created for interface and second for Refrigerator class. Second object right now.
The most general answer to the general part of your question (why should I use polymorphism?) is that polymorphism realizes a few critical object-oriented design principles, for example:
code reuse:
By putting any code that is common to all of your 'cooling-machines' into cooling-machine, you only need to write that code once and any edits to that code trickle down instantly.
abstraction:
Human brains can only keep track of so much stuff, but they are good at categories and hierarchies. This helps understand what's happening in a big program.
encapsulation:
each class hides the details of what it's doing and just builds on the interface of the base class.
separation of concerns:
a lot of object oriented programming is about assigning responsibilities. Who is going to be in charge of that? Specialized concerns can go in subclasses.
So polymorphism is just part of the bigger oo picture, and the reasons for using it sometimes only make sense if you are going to try and do 'real' oo programming.
A simple use case of polymorphism is that you can have an array of coolingMachines where element 0 is a refrigator and element 1 is an AirConditioner etc...
You do not need to preform any checks or make sure which object you are dealing with in order to call trip or start etc.
This can be a great benefit when taking input from a user and having to iterate over all the objects and call similar functions
I'll give an easy to understand example. Lets say you have some json
{"a":[1,2],"sz":"text", "v":3, "f":1.2}
Now lets say programmatically you want to list the name, type and value. Instead of having a switch() for each type (array for a, string for sz, etc) you can just have a base type and call a function which does its job. It is also more cpu efficient than using a switch with a dozen types.
Then there are plugins, libs and foreign code with interface reasons.
Using your objects polymorphically also helps to create factories or families of related classes which is an important part of how Factory Design Pattern is implemented. Here's a very basic example of polymorphic factory:
public CoolingMachine CreateCoolingMachines(string machineType)
{
if(machineType == "ref")
return new Refrigerator();
//other else ifs to return other types of CoolingMachine family
}
usage of calling above code:
CoolingMachine cm = CreateCoolingMachine("AC"); //the cm variable will have a reference to Airconditioner class which is returned by CreateCoolingMachines() method polymorphically
Also, imagine that you have a method as below that uses concrete class parameter Refrigerator:
public void UseObject(Refrigerator refObject)
{
//Implementation to use Refrigerator object only
}
Now, if you change above implementation of UseObject() method to use most generic base class parameter, the calling code would get advantage to pass any parameter polymorphically which can then be utilized inside the method UseObject():
public void UseObject(CoolingMachine coolingMachineObject)
{
//Implementation to use Generic object and all derived objects
}
Above code is now more extensible as other subclasses could be added later to the family of
CoolingMachines, and objects of those new subclasses would also work with the existing code.
I am new to java and I am trying to create an XML document and clone a specific node (minus the textnode) of this document over and over again. Someone answered me and said that I should subclass the node and override the cloning. So my question is what is sub-classing?
Subclassing means to define a new class that has the properties of an old class (the "superclass") with some changes.
In this case, your original responder is saying something like this:
Say you have a base class Base which has a method getTwo like so:
class Base {
public int getTwo(){ return 2;}
}
You decide you want a new class that still have a method getTwo but that returns the string "two" instead of the number 2. You could define it as
class Subclass extends Base {
public String getTwo() { return "two"; }
}
We say Subclass is a subclass of -- or more commonly, "is a kind of" -- Base.
Beyond that, you'd be best off to read a book on object-oriented programming with Java. I'm fond of Thinking in Java, which has the added advantage that it's available freely on line.
#Charlie Martin has explained what subclassing means.
However, it is not clear that you've been given good advice. If you are creating the XML document by assembling a DOM in memory, a better approach would be to create a helper class with static methods that perform the sequence of DOM node operations that you need to do.
In short Answer : A Superclass can be Subclassed - That means for a specific class we can find/create a subclass that extend it.
Subclass represents is a relationship in Object-Oriented Programming (Inheritance).
For example
The Circle is a Shap.
So we can say:
The Circle class is a subclass of Shape class.
I have a bunch of classes extending an abstract Base class.
Each subclass takes an array as in the constructor, (different length depending on class).
These classes could be written by other people.
What is the best way to figure out the length of the array the class needs?
I could:
(A) Require that each derived class have a static method, returning the length.
However, the base class cannot enforce this, since abstract static methods does not work in java.
(B) Each derived class have a constructor with no arguments, and I construct
such classes just to be able to call the countParameters() method, that
I can enforce from the Base class. This feels "cludgy", since I am not interested in creating such object, but only need some info about it.
The reason is that I am creating a GUI, that gives the user the ability to create
instances of Derived classes, but each Derived class takes different number of parameters.
That is, I need to know how to draw the GUI before I can create the classes.
EDIT:
I could just require that each Derived class have a private
constructor, with no arguments, and using reflection I can call the countParameters() method.
EDIT2: Actually, what I am interested in, is what the names of the parameters are.
That is, if the class Derived have the constructor
public Derived(double name1,double name2,...)
I need a way to generate the String[] array
{name1,name2,...}
I guess this would be impossible to do without creating an instance of the class,
but for the user to be able to create such class, he/she needs the parameter names!
Moment 22.
It sounds like you need the Factory Pattern.
In general, it's a bad idea for a base class to know the set of it's descendant's. So you define another class whose job it is to know that.
If you have something like a Shape, with ThisShape and ThatShape as derived classes, then a ShapeCreator will handle the job of creating the specific set of shapes your program supports, giving each one the arguments it needs.
It's not quite clear what you're trying to achieve, but I wonder: Do the subclasses really have to take a single parameter with an array, as opposed to a list of parameters?
Constructor<?> ctor = Test.class.getConstructors()[0];
int parameterCount = ctor.getParameterTypes().length;
ctor.newInstance(new Object[parameterCount]);
how about this code:
public absract Base {
public abstract int size();
public Base(Object[] objs) {
if (objs.length != size()) {
throw new IllegalArgumentException();
}
//rest of your code.
}
each child class needs to implement size method.
hope its help.
I'd go with method A. You can't get the compiler to enforce the existence of such a method, but you can certainly enforce it in your program - no method, no work!
Seriously, this whole scheme is a bit brittle and I can't think of a way to make it significantly better. An incorrect implementation of those subclasses will bomb out, that's life.
A possible remedy would be for you to provide a set of interfaces for those subclasses, such as
SubClassTaking2Args
SubClassTaking3Args
...
and requiring your sub's to implement one of those as a marker interface. But that's just more bureaucracy with little more effect.