Generic inheritance in java - java

In c++ we can write:
#include <iostream>
class Base1
{
public: void test() { std::cout << "Base 1" << std::endl; }
};
class Base2
{
public: void test() { std::cout << "Base 2" << std::endl; }
};
template<class T>
class Derived: public T
{
};
int main()
{
Derived<Base1> d1;
Derived<Base2> d2;
d1.test();
d2.test();
}
To get templated inheritance.
Can the same be done in java using generics?
Thanks.
Edit: Adding more info about my intentions
In my scenario I have two subclasses, Sprite and AnimatedSprite (which is a subclass of Sprite). The next step is a PhysicalSprite that adds physics to the sprites, but I want it to be able to inherit from both Sprite and AnimatedSprite.

No. C++'s templates are much stronger than Java's generics. Generics in Java are only for ensuring proper typing during compile time and are not present in the generated bytecode - this is called type erasure.
In my scenario I have two subclasses, Sprite and AnimatedSprite (which is a subclass of Sprite). The next step is a PhysicalSprite that adds physics to the sprites, but I want it to be able to inherit from both Sprite and AnimatedSprite.
Inheritance is not the only form of code reuse. This use case can be handled with other patterns as well, such as simple decoration. Consider something akin to the following:
interface Sprite { ... }
class StaticSprite implements Sprite { ... }
class AnimatedSprite implements Sprite { ... }
class PhysicalSprite implements Sprite, Physics {
PhysicalSprite(Sprite inner) { ... }
...
}
PhysicalSprite would in this case delegate the Sprite parts to some Sprite instance provided in the constructor. It would then be free to add its own handling for the Physics part.

Alas, no.
Unlike C++, which can be thought to emit a different class definition for every instantiation of a template, all instantiations of a generic type share the same runtime class in Java, and therefore have the same method definitions. Generics (in Java) are compile-time and not tracked at runtime.
Therefore, the Java Language Specification explictly forbids to specify a type paramater as superclass or implemented interface:
The optional extends clause in a normal class declaration specifies the direct superclass of the current class.
Super: extends ClassType
where ClassType is a qualified or unqualified class name (with optional type arguments)
Workarounds
Use the decorator pattern if you don't need to override methods invoked by the super class.
Generate a dedicated subclass for each instantiation of the template. You can do so at runtime using, for instance, Javassist, or using source code transformations at compile time.

No, not in exact same way. But if you tell us what exactly you want to do, I'm pretty sure there'll be some elegant way to do that. I just don't see any need for templates/generics in your example.
In particular, it looks like Base1 and Base2 might benefit from common interfaces with method test.

Hm.. Do you need decorator?

Related

Generic method in interface returns a non-checked cast

So I have a series of related interfaces one that contains other 3 (enforced by setters and getters).
While instances of this interfaces are OK to remain as just interface contracts while they are managed (stored and retrieved from a map); when they reach a processing bean they need to be able to reveal them-self as the implemented class they are.
So I was able to this doing the following:
public interface IState<S extends IState> {
<G extends GameData> G getGameData();
<G> S setGameData(G gameDataIO);
<P> P getPlayer();
<P> S setPlayer(P player);
<GS> GS getGameState();
<GS> S setGameState(GS gameState);}
The default implementation:
public class DefaultStateNG implements IStateNG<DefaultStateNG> {
private GameData gameDataIO;
private IPlayerState player;
private IGameState gameState;
#Override
public <G extends GameData> G getGameData() {
return (G) gameDataIO;
}
#Override
public <G> DefaultStateNG setGameData(G gameDataIO) {
this.gameDataIO = (GameData) gameDataIO;
return this;
} //..... other accessor methods implemented
So when I use them in the processor bean they do not need to be casted into the appropriate implementation of the interface.
The problem arises when a unchecked cast in throw when casting in the returned type. I don't know how to handle such warning. I mean I am setting gameDataIO as Game data type and the return is supposed to be a GameData type. Why the warning?. I tried every kind of casting, the only one that works without warning so far is is pass the expected class as argument and then use type.cast(returnedObject).
Any hint will be appreciated.
When your interface defines generic methods like this:
<G extends GameData> G getGameData();
The compiler knows that <G> must extend or implement GameData, but the exact implementation represented by G will be inferred at the site of the code that calls the getGameData() method.
When you implement that method:
#Override
public <G extends GameData> G getGameData() {
return (G) gameDataIO;
}
Your implementation here knows nothing about any potential call sites. It's supposed to return the specific subtype needed by the caller (G), which it cannot do. You're casting, but the compiler can't verify that it's safe (because it's not) and so you get an unchecked warning.
Pretend I write a class MyGameData extends GameData and write this in my code:
IState<?> state = ... // TODO
MyGameData mgd = state.getGameData();
In this case, <G> is bound to the specific type MyGameData, which meets your API requirement that it must inherit from GameData. But then your code returns a plain GameData not my specific subclass and results in a ClassCastException at runtime.
The same goes for most of your other methods. Either return the base type (GameData, etc.) without making the getters, etc., generic methods or you'll have to add type parameters G, GS, and P to the IState interface instead of on a per-method basis.
EDIT to add, based on this comment:
GameData, Player and other are interfaces whose implementations are injected by Spring on start. So I have interfaces just to ensure basic functionalities, but the implemented classes need to be known by the processor. I did a first version without generics, but I ended doing tons of type casting making the code unreadable.
You're describing symptoms of a tightly-coupled system. Interfaces are a tool for defining loosely-coupled systems, as these are often considered a better design. I encourage you to consider why in your design the processor needs to be so aware of the implementation type of the other interfaces. Is it because the interfaces themselves do not fully describe the functional behavior needed by implementations of that interface?
Well I came around with solution which is to define the type on the entry point to the implemented processor. I was no able to find a way to to set the type declaration using generic methods (at least no without to having to do a un unchecked casting).
After William I am clear the declarations must be made, and my processor bean is where all other bean get connected together, hence it made sense that there the types are declared. Unluckily for me the state is the I/O object of my processing method, so it also need to declared in the processor including it's contained classes.
Something like:
#Component
public class KenoManager implements IGenericGame<DefaultState<
KenoData,
DefaultPlayer,
KenoGameState,
DefaultSystemState>> {
public DefaultState processInit(DefaultState<
KenoData,
DefaultPlayer,
KenoGameState,
DefaultSystemState> state) {
return null;
}
When it come the config file I can use wildcards ? to fill the declaration and to make the injection of certain beans generic.

Java Inheritance - The difference between data types when creating objects [duplicate]

What is polymorphism, what is it for, and how is it used?
If you think about the Greek roots of the term, it should become obvious.
Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.
The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a series of lines.
By making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:
shape.Draw()
to get the correct behavior for any shape.
This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle().
Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)
(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The monomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.
Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.
Sometimes, you should just quit while you're behind :-)
Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.
Here is an example in C#. Create four classes within a console application:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
Now create the following in the Main() of the module for the console application:
public void Main()
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(
string.Format("A {0} has {1} wheels.",
v.GetType().Name, v.Wheels));
}
}
In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.
We then add a Bicycle, Car and Truck to the list.
Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.
This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.
I hope that this helps you.
From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.
Polymorphism is a long word for a very simple concept.
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.
A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.
If anybody says CUT to these people
The Surgeon
The Hair Stylist
The Actor
What will happen?
The Surgeon would begin to make an incision.
The Hair Stylist would begin to cut someone's hair.
The Actor would abruptly stop acting out of the current scene,
awaiting directorial guidance.
So above representation shows What is polymorphism (same name, different behavior) in OOP.
If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-
Answer - Door / Windows
Wondering How?
Through Door / Window - a person can come, air can come, light can come, rain can come, etc.
To understand it better and in a simple manner I used above example..
If you need reference for code follow above answers.
Simple Explanation by analogy
The President of the United States employs polymorphism. How? Well, he has many advisers:
Military Advisers
Legal Advisers
Nuclear physicists (as advisers)
etc etc.
Everyone Should only be responsible for one thing: Example:
The president is not an expert in zinc coating, or quantum physics. He doesn't know many things. But he does know how to run the country.
It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. This makes it easier to maintain code, especially if when you are making changes. Changes are inevitable. When things do change, you do not want to break other parts of your application. Presidents should stick to running the country, rather than getting into the nitty-gritty of specialist areas:
Why is that a bad idea for a president to know all those specific things?
If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.
For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.
Is there a better approach?
There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.
He can use a polymorphic approach to running the country.
Example - of using a polymorphic approach:
All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:
public class MisterPresident
{
public void RunTheCountry()
{
// assume the Petraeus and Condi classes etc are instantiated.
petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
condolezza.Advise(); // # she says negotiate trade deal with Iran
healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
}
}
This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".
What you DON"T want:
public class MisterPresident
{
public void RunTheCountry()
{
// people walk into the Presidents office and he tells them what to do
// depending on who they are.
// Fallujah Advice - Mr Prez tells his military exactly what to do.
petraeus.IncreaseTroopNumbers();
petraeus.ImproveSecurity();
petraeus.PayContractors();
// Condi diplomacy advice - Prez tells Condi how to negotiate
condi.StallNegotiations();
condi.LowBallFigure();
condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();
// Health care
healthOfficial.IncreasePremiums();
healthOfficial.AddPreexistingConditions();
}
}
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.
This allows the president to do what he does best: set general policy, look good and play golf :P.
How is it actually implemented - through a base class or a common interface
That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)
In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.
This would be ideal
public class MisterPresident
{
// You can pass in any advisor: Condi, HealthOfficials,
// Petraeus etc. The president has no idea who it will
// be. But he does know that he can ask them to "advise"
// and that's all Mr Prez cares for.
public void RunTheCountry(IAdvisor governmentOfficer)
{
governmentOfficer.Advise();
}
}
public class USA
{
MisterPresident president;
public USA(MisterPresident president)
{
this.president = president;
}
public void ImplementPolicy()
{
IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
president.RunTheCountry(governmentOfficer);
}
}
Summary
All that you really need to know is this:
The president doesn't need to know the specifics - those are left to others.
All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )
I really hope it helps you. If you don't understand anything post a comment and i'll try again.
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
Polymorphism:
It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.
Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:
Just as the fields of a C structure are in a protected namespace, so
are an object’s instance variables.
Method names are also protected. Unlike the names of C functions,
method names aren’t global symbols. The name of a method in one
class can’t conflict with method names in other classes; two
very different classes can implement identically named methods.
Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.
The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.
Examples:
Example-1: Here is a simple example written in Python 2.x.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.
Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.
But each have their own advanced features and more advanced technology involved in their move behavior.
Now let us create a basic type Car
Car.java
public class Car {
int price;
String name;
String color;
public void move(){
System.out.println("Basic Car move");
}
}
Let us implement the Ford Car example.
Ford extends the type Car to inherit all its members(properties and methods).
Ford.java
public class Ford extends Car{
public void move(){
System.out.println("Moving with V engine");
}
}
The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.
Honda.java
public class Honda extends Car{
public void move(){
System.out.println("Move with i-VTEC engine");
}
}
Just like Ford, Honda also extends the Car type and implemented the move method in its own way.
Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.
PolymorphismExample.java
public class PolymorphismExample {
public static void main(String[] args) {
Car car = new Car();
Car f = new Ford();
Car h = new Honda();
car.move();
f.move();
h.move();
}
}
Polymorphism Example Output:
In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.
Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.
So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.
But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.
So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.
Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:
Polymorphism in object oriented programming
Type polymorphism
EDIT: fixed broken links.
Polymorphism is this:
class Cup {
int capacity
}
class TeaCup : Cup {
string flavour
}
class CoffeeCup : Cup {
string brand
}
Cup c = new CoffeeCup();
public int measure(Cup c) {
return c.capacity
}
you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type
I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:
Treating a derived type as if it were it's base type.
There are plenty of examples above that show this in action, but I feel this is a good concise answer.
(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )
http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife
read on from this part:
..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.
Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:
Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.
Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.
The term polymorphism comes from:
poly = many
morphism = the ability to change
In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:
A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.
Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)
So this technique lets you build stuff that can be "looked" at from different angles.
Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)
Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.
Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.
If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.
This is just an example of a possible design (in Java):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
I've provided a high-level overview of polymorphism for another question:
Polymorphism in c++
Hope it helps. An extract...
...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:
Type1 x;
Type2 y;
f(x);
f(y);
Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.
( continued at Polymorphism in c++ )
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
Polymorphism is an ability of object which can be taken in many forms.
For example in human class a man can act in many forms when we talk about relationships.
EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:
public class PolymorphismExample {
public static abstract class Vehicle
{
public int wheels(){
return 0;
}
}
public static class Bike extends Vehicle
{
#Override
public int wheels()
{
return 2;
}
}
public static class Car extends Vehicle
{
#Override
public int wheels()
{
return 4;
}
}
public static class Truck extends Vehicle
{
#Override
public int wheels()
{
return 18;
}
}
public static void main(String[] args)
{
Vehicle bike = new Bike();
Vehicle car = new Car();
Vehicle truck = new Truck();
System.out.println("Bike has "+bike.wheels()+" wheels");
System.out.println("Car has "+car.wheels()+" wheels");
System.out.println("Truck has "+truck.wheels()+" wheels");
}
}
The result is:
For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.
Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:
// Class definitions
class Fraction
{
public $numerator;
public $denominator;
public function __construct($n, $d)
{
// In real life, you'd do some type checking, making sure $d != 0, etc.
$this->numerator = $n;
$this->denominator = $d;
}
public function display()
{
echo $this->numerator . '/' . $this->denominator;
}
}
class ComplexNumber
{
public $real;
public $imaginary;
public function __construct($a, $b)
{
$this->real = $a;
$this->imaginary = $b;
}
public function display()
{
echo $this->real . '+' . $this->imaginary . 'i';
}
}
// Main program
$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);
echo 'This is a fraction: '
$fraction->display();
echo "\n";
echo 'This is a complex number: '
$complex->display();
echo "\n";
Outputs:
This is a fraction: 1/2
This is a complex number: 1 + 2i
Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.
At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:
$userNumberChoice = $_GET['userNumberChoice'];
switch ($userNumberChoice) {
case 'fraction':
$userNumber = new Fraction(1, 2);
break;
case 'complex':
$userNumber = new ComplexNumber(1, 2);
break;
}
echo "The user's number is: ";
$userNumber->display();
echo "\n";
In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.
Polymorphism literally means, multiple shapes. (or many form) :
Object from different classes and same name method , but workflows are different.
A simple example would be:
Consider a person X.
He is only one person but he acts as many.
You may ask how:
He is a son to his mother.
A friend to his friends.
A brother to his sister.
Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.
for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well.
so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.
Polymorphism:
Different execution according to the instance of the class, not the type of reference variable.
An interface type reference variable can refer to any of the class instances that implement that interface.
What is polymorphism?
Polymorphism is the ability to:
Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type:
This is dynamic polymorphism.
Define several methods having the save name but having differents parameters:
This is static polymorphism.
The first if the historical definition and the most important.
What is polymorphism used for?
It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.
Strong and weak typing
Sample
Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.
public class Shape
{
public virtual void Draw()
{
DoNothing();
}
public virtual void Draw(int timeout)
{
DoNothing();
}
}
public class Point : Shape
{
int X, Y;
public override void Draw()
{
DrawThePoint();
}
}
public class Line : Point
{
int Xend, Yend;
public override Draw()
{
DrawTheLine();
}
}
public class Rectangle : Line
{
public override Draw()
{
DrawTheRectangle();
}
}
var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
foreach ( var shape in shapes )
shape.Draw();
Here the Shape class and the Shape.Draw() methods should be marked as abstract.
They are not for to make understand.
Explaination
Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.
With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.
More readings
C# - Polymorphism (Level 1)
Polymorphism in Java (Level 2)
Polymorphism (C# Programming Guide)
Virtual method table
Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).
Do remember that each class must be saved in separate files.
The following code exemplifies Polymorphism:
The SuperClass:
public class Parent {
//Define things that all classes share
String maidenName;
String familyTree;
//Give the top class a default method
public void speak(){
System.out.println("We are all Parents");
}
}
The father, a subclass:
public class Father extends Parent{
//Can use maidenName and familyTree here
String name="Joe";
String called="dad";
//Give the top class a default method
public void speak(){
System.out.println("I am "+name+", the father.");
}
}
The child, another subclass:
public class Child extends Father {
//Can use maidenName, familyTree, called and name here
//Give the top class a default method
public void speak(){
System.out.println("Hi "+called+". What are we going to do today?");
}
}
The execution method, references Parent class to start:
public class Parenting{
public static void main(String[] args) {
Parent parents = new Parent();
Parent parent = new Father();
Parent child = new Child();
parents.speak();
parent.speak();
child.speak();
}
}
Note that each class needs to be declared in separate *.java files.
The code should compile.
Also notice that you can continually use maidenName and familyTree farther down.
That is the concept of polymorphism.
The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.
Hope this helps and makes it clear.
I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!
Polymorphism allows the same routine (function, method) to act on different types.
Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.
Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
Subtype polymorphism allows a routine to act on any subtype of its parameters.
Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.
See also:
http://wiki.c2.com/?CategoryPolymorphism
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++:
Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.
Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.
Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.
By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).
This is where I found the above definition. Around 50 minutes into the video the instructor explains the above.
https://www.youtube.com/watch?v=TMuno5RZNeE
First off all I believe that polymorphism is an essential part of object-oriented programming that enables us to define behavior shared by multiple classes but can be changed for each class separately. I would like share something from my experience in order to help in simple examples how to downsize complexity of code.
I can understand that in some ways it could be constructive for reusing code and keeping the maintainability part. It makes them less painful. But, like any other programming method, there are times when polymorphism might not be the best option.
Consider a base class called Car with a method called StartEngine() that tells the engine how to start. Suppose you have derived classes like MercedesBenzCar and TeslaModelSCar. In that case, you might be able to use polymorphism to define the StartEngine() method in the base Car class and then override that method in the derived classes to provide the specific implementation for each type of car. But this can get you into trouble. Let's review some code.
/// <summary>
/// Base class for car objects
/// </summary>
public abstract class Car
{
public virtual void StartEngine()
{
Console.WriteLine(value: "Car engine has been started.");
}
public virtual void StopEngine()
{
Console.WriteLine(value: "Car engine has been stopped.");
}
}
Once we have defined the base class, let's define derived classes.
/// <summary>
/// Example of polymorphism in C# using abstract classes on Mercedes Benz cars
/// </summary>
public class MercedesBenzCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public override void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
/// <summary>
/// Example of polymorphism in C# using abstract classes on Tesla Electric Cars
/// </summary>
public sealed class TeslaModelSCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public override void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
So what's the point? In this example, the StartEngine() and StopEngine() methods of the base Car class show how to start and fundamentally start or stop a car. MercedesBenzCar and TeslaModelSCar classes override these methods to provide their implementations of the behavior unique to electric and fuel cars, respectively. So, it makes more sense to define the behavior directly in the derived classes instead of using polymorphism to describe it in the base class.
As you can see, this design might not be a good idea if the StartEngine() or StopEngine() methods behave very differently in each derived class. This is because it would take a lot of work to define a meaningful implementation of the StartEngine() or StopEngine() methods in the base class. In this case, it might be better to directly define the StartEngine() or StopEngine() method in the derived classes instead of using polymorphism.
How can we find a solution to this problem?
Let's look at this example again and see how inheritance and polymorphism can be used in C# when the behavior of the derived classes is very different. 
Regarding refactoring, I'd like to suggest that interfaces or contracts be introduced as a potential resolution for this problem and give us a better design. Before we talk about interfaces, let's go over what they are. Inferences can be considered a proposal for a class or structure that describes they properties and methods.
A new version of C# could have a default implementations, but let's not make things harder than they need to be. If you want to learn more about it, check this link. In short, they say how the members signatures should look but not how implementation should look.
I would like to propose that the ICar interface defines two methods, StartEngine() and StopEngine(). The MercedesBenzCar and TeslaModelSCar classes should implement the ICar interface, which means that we can get rid of the abstract class here and convert it into an interface. So, Car should go to ICar. 
Why? This can be a more flexible and sustainable design than inheritance because you can add or remove ICar interfaces from a class without affecting the class inheritance hierarchy. Let's now refactor our above solution to see it in practice.
/// <summary>
/// Base interface for all car types.
/// </summary>
public interface ICar
{
/// <summary>
/// Use this method to turn on the car engine.
/// </summary>
void StartEngine();
/// <summary>
/// Use this method to turn off the car engine.
/// </summary>
void StopEngine();
}
Once is interface ICar has been implemented, now is the time we refactor or concrete classes.
/// <summary>
/// Example of using the interface ICar for the class TeslaModelSCar.
/// </summary>
public sealed class TeslaModelSCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
/// <summary>
/// Example of using the interface ICar for the class MercedesBenzCar.
/// </summary>
public class MercedesBenzCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
The refactoring process is now complete. It is now time to look at how to make use of it.
ICar teslaModelS = new TeslaModelSCar();
ICar mercedesBenz = new MercedesBenzCar();
teslaModelS.StartEngine();
mercedesBenz.StartEngine();
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
teslaModelS.StopEngine();
mercedesBenz.StopEngine();
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Imagine for a moment that we have a collection of cars in the garage and that there is another way to use it to start the cars engines in sequential order.
var carsInGarage = new ICar[2] { new TeslaModelSCar(), new MercedesBenzCar() };
foreach (var car in carsInGarage)
{
car.StartEngine();
}
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
foreach (var car in carsInGarage)
{
car.StopEngine();
}
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Again, polymorphism is a powerful object-oriented programming method that lets you define behavior shared by more than one class. But, like any other programming method, there are times when polymorphism might not be the best option. I believe that there are situation when we should consider the interface:
When a class's behavior is very different from that of its base
class. When there are a lot of classes that are based on it.
When performance is essential.
When you need to support more than one inheritance since C# doesn't do it by itself.
When deciding whether or not to use polymorphism in your code, I believe it's essential to keep these things in mind.
Cheers! 👋

Difference between inheritance & polymorphism [duplicate]

This question already has answers here:
What is the main difference between Inheritance and Polymorphism?
(18 answers)
Closed 1 year ago.
I am having issues understanding what exactly polymorhism is and how it differs from inheritance. I have researched the web and found many answers that gives very technical deffinitions on what polymorphism is but nothing in which i really understand too well. I have come up with an example that might be polymorphism but may not be.
MY example:
Say you have a Gym with many levels of membership.
basic member
silver member
gold member
and each class is a basic member but has more function
class basicMember(){
private double rate = 10;
privatedbl poolPrice = 5;
public void setRate (dbl in);
{
rate = in;
}
public dbl getRate()
{
return rate;
}
public dbl getPoolPrice()
{
return poolPrice;
}
}
class silverMember extends basicRate()
{
private dbl poolPriceDis = .9;
setRate(15);
public dbl getPoolPriceDis(){
return getPoolPrice() * poolPriceDis;
}
}
class goldMember extends basicRate(){
private dbl poolPriceDis = .85;
setRate(20);
public dbl getPoolPriceDis(){
return getPoolPrice() * poolPriceDis;
}
}
Would this be an example of inheritance or polymorphism or both? Please explain.....
Your example demonstrates inheritance.
Polymorphism lets you call methods of a class without knowing the exact type of the class. It deals with how the program decides which methods it should use, depending on what type of object it has. If you have a Animal, which has a eat method, and you have a Cow which extends Animal, which has its own implementation of Eat, which method gets called is depends if you have a pointer to Animal or a Cow.
Polymorphism allows you to write a method that works for any Animal:
public void pet(Animal animal) {
...
}
This method would accept Dog, Cat, etc, including subclasses of Animal that are yet to be written.
Inheritance lets derived classes share interfaces and code of their base classes. It is when a 'class' derives from an existing 'class'. So if you have a Animal class, then you have a Cow class that extends Animal, Cow inherits all the things that Animal has (depending on access modifiers).
public class Animal {...}
public class Dog extends Animal {...}
Dog d = new Dog();
d.DoAnimalStuff();
Inheritance in any language is a type of polymorphism. Polymorphism is the ability for multiple things (multiple classes, multiple functions, etc) to be treated in the same way. Inheretance allows that because you can treat any type as the base class. Another form of polymorphism in Java is generics- you can pass in any type, so long as it defines all the functions you need.
Inheritance is one object having the same logic as another object with some extra logic. Inheritance saves you lines of code.
Polymorphism is allowing multiple objects to be type-safely stored in the same place, and operated on with the same code
suppose d inherits/impliments from b
Base b = new Derived d;
b.DoThingsThatBasesCanDo();
Your example is just inheritance, but it can become polymorphism depending on your usage
It would be even more polymorphic if poolPriceDis was a member of your base class, and you either override it in your derived classes or initialized it in your respective class's constructers
Using Java...
Inheritance is the concept of defining a class that adds to, or extends, another class. It is also possible to change a class. For example, a boss might extend an employee by adding the ability to ask for a raise.
public class Employee
{
...
}
public class Boss extends Employee
{
public void askForRaise(){}
}
Polymorphism, can be used a few ways. Lets look at two of them. First, different classes can do different things with the same method, for example, we can define a Shape class that represents all shapes and has a draw method.
public abstract class Shape
{
public abstract void draw();
}
A square will implement draw to draw a square, while a circle will draw a circle. Both draw, but do different things, this is the first kind of polymorphism.
public class Square extends Shape
{
public void draw(){...}
}
public class Circle extends Shape
{
public void draw(){...}
}
It is worth noting that we also used inheritance in this example. Square and Circle inherit from Shape so they have all of the methods and properties that Shape has.
A second kind of polymorphism that shows up in Java is the ability to have the same method with different arguments. For example, a number might have an add method that takes an integer and another that takes a double:
public class MyNumber
{
public void add(int i){...}
public void add(double d){...}
}
Having two versions of the same method is another form of polymorphism.
Polymorphism comes in many shapes and sizes, one of which is inheritance.
Inheritance lets you use objects as if they were of the same class, where in reality they may be different classes. See your example code.
Overloading lets you use functions with parameters of different types as if they were the same. For example: add("hello", "world") and add(1, 2).
Parametrization lets you use functions or classes that don't care about the type, as long as you tell it in advance. For example: Vector<Float> versus Vector<String>.
In all cases you see this "different/many" (poly) acting as the "same/similar shape" (morph).
Quoting Mr. Cay Horstmann from Object Oriented Design & Patterns:
The ability to select the appropriate method for a particular object is
called polymorphism. (The term "polymorphic" literally means "having
multiple shapes".)
and
You use inheritance to model a relationship between classes in which
one class represents a more general concept and another a more
specialized concept.
In your case, you're just using inheritance. But if you would override, let's say, your setRate() method in the silverMember class and had something like this in the main:
basicMember member = new silverMember();
member.setRate(20);
then the setRate() of the silverMember class is invoked although you have a basicMember variable. That's polymorphism.
--
I wouldn't be true to myself if i did not advise you not to do this interview if you don't know this kind of stuff. Try reading the book i quoted in the beginning of the comment.

Java interfaces and types

Let's say you have some Java code as follows:
public class Base{
public void m(int x){
// code
}
}
and then a subclass Derived, which extends Base as follows:
public class Derived extends Base{
public void m(int x){ //this is overriding
// code
}
public void m(double x){ //this is overloading
// code
}
}
and then you have some declarations as follows:
Base b = new Base();
Base d = new Derived();
Derived e = new Derived();
b.m(5); //works
d.m(6); //works
d.m(7.0); //does not compile
e.m(8.0); //works
For the one that does not compile, I understand that you are passing in a double into Base's version of the m method, but what I do not understand is... what is the point of ever having a declaration like "Base b = new Derived();" ?
It seems like a good way to run into all kinds of casting problems, and if you want to use a Derived object, why not just go for a declaration like for "e"?
Also, I'm a bit confused as to the meaning of the word "type" as it is used in Java. The way I learned it earlier this summer was, every object has one class, which corresponds to the name of the class following "new" when you instantiate an object, but an object can have as many types as it wants. For example, "e" has type Base, Derived, (and Object ;) ) but its class is Derived. Is this correct?
Also, if Derived implemented an interface called CanDoMath (while still extending Base), is it correct to say that it has type "CanDoMath" as well as Base, Derived, and Object?
I often write functions in the following form:
public Collection<MyObject> foo() {}
public void bar(Collection<MyObject> stuff){}
I could just as easily have made it ArrayList in both instances, however what happens if I later decide to make the representation a Set? The answer is I have a lot of refactoring to do since I changed my method contract. However, if I leave it as Collection I can seamlessly change from ArrayList to HashSet at will. Using the example of ArrayList it has the following types:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
There are a number of cases where confining yourself to a particular (sub)class is not desired, such as the case you have where e.m(8.0);. Suppose, for example, you have a method called move that moves an object in the coordinate graph of a program. However, at the time you write the method you may have both cartesian and radial graphs, handled by different classes.
If you rely on knowing what the sub-class is, you force yourself into a position wherein higher levels of code must know about lower levels of code, when really they just want to rely on the fact that a particular method with a particular signature exists. There are lots of good examples:
Wanting to apply a query to a database while being agnostic to how the connection is made.
Wanting to authenticate a user, without having to know ahead of time the strategy being used.
Wanting to encrypt information, without needing to rip out a bunch of code when a better encryption technique comes along.
In these situations, you simply want to ensure the object has a particular type, which guarantees that particular method signatures are available. In this way your example is contrived; you're asking why not just use a class that has a method wherein a double is the signature's parameter, instead of a class where that isn't available. (Simply put; you can't use a class that doesn't have the available method.)
There is another reason as well. Consider:
class Base {
public void Blah() {
//code
}
}
class Extended extends Base {
private int SuperSensitiveVariable;
public setSuperSensistiveVariable(int value) {
this.SuperSensistiveVariable = value;
}
public void Blah() {
//code
}
}
//elsewhere
Base b = new Extended();
Extended e = new Extended();
Note that in the b case, I do not have access to the method set() and thus can't muck up the super sensitive variable accidentally. I can only do that in the e case. This helps make sure those things are only done in the right place.
Your definition of type is good, as is your understanding of what types a particular object would have.
What is the point of having Base b = new Derived();?
The point of this is using polymorphism to change your implementation. For example, someone might do:
List<String> strings = new LinkedList<String>();
If they do some profiling and find that the most common operation on this list is inefficient for the type of list, they can swap it out for an ArrayList. In this way you get flexibility.
if you want to use a Derived object
If you need the methods on the derived object, then you would use the derived object. Have a look at the BufferedInputStream class - you use this not because of its internal implementation but because it wraps an InputStream and provides convenience methods.
Also, I'm a bit confused as to the meaning of the word "type" as it is used in Java.
It sounds like your teacher is referring to Interfaces and Classes as "types". This is a reasonable abstraction, as a class that implement an interface and extends a class can be referred to in 3 ways, i.e.
public class Foo extends AbstractFoo implements Comparable<Foo>
// Usage
Comparable<Foo> comparable = new Foo();
AbstractFoo abstractFoo = new Foo();
Foo foo = new Foo();
An example of the types being used in different contexts:
new ArrayList<Comparable>().Add(new Foo()); // Foo can be in a collection of Comparable
new ArrayList<AbstractFoo>().Add(new Foo()); // Also in an AbstractFoo collection
This is one of the classic problems on object oriented designs. When something like this happens, it usually means the design can be improved; there is almost always a somewhat elegant solution to these problems....
For example, why dont you pull the m that takes a double up into the base class?
With respect to your second question, an object can have more than one type, because Interfaces are also types, and classes can implement more than one interface.

Overriding rules in C++

Coming from a Java perspective I was surprised to find that you can only override base methods that have the virtual keyword.
In Java you use the final keyword to declare that a method can't be overridden.
I had the idea in my head that you only rarely want to prohibit overriding so that someone can extend your class how they see fit.
So in C++ if you feel that someone might want to at some stage inherit from your class (maybe years later someone thinks its a cool idea) do you make all your methods virtual?
Or is there some critical reason for wanting to prohibit this in C++ that I am unaware of?
for Reference this was the experimenting i did in each language:
Java
public class Base {
void doSomething(){
System.out.println("Doing the base thing");
}
}
public class Derived extends Base {
void doSomething(){
System.out.println("Doing the derived thing");
}
public static void main(String... argv){
Base object = new Derived();
object.doSomething();
}
}
C++
class Base
{
public:
Base(void);
~Base(void);
virtual void doSomething();
};
void Base::doSomething(){
std::cout << "I'm doing the base thing\n" << std::endl;
}
class Derived :
public Base
{
public:
Derived(void);
~Derived(void);
void doSomething();
};
void Derived::doSomething(){
std::cout << "I'm doing the dervied thing" << std::endl;
}
int main(void){
Base * object = new Derived;
object->doSomething();
return 0;
}
duffymo and Als are steering you in the right direction. I just wanted to comment on one thing you said:
So in C++ if you feel that someone might want to at some stage inherit
from your class (maybe years later someone thinks its a cool idea) do
you make all your methods virtual?
From a software engineering perspective: if you don't have an immediate use for inheritance and aren't using interfaces, then I don't recommend declaring your methods virtual.
Virtual methods come with an ever so slight performance degradation. For non-critical code paths the perf impact is likely negligible. But for class methods that get invoked a lot, it can add up. The compiler can't do as much inlining and direct linkage. Instead, the virtual method to be invoked has to be looked up in the v-table array at runtime.
When someone on my coding team starts off a design conversation with "someone might want at some point later..." that's when my "future proofing" anti-pattern alarm goes off. Designing for extensibility is one thing, but "features for the future" should be put off until then.
And besides - the guy years later who thinks it's a cool idea - Let him be the one to own converting the class methods to be virtual. You'll be onto bigger projects by then anyway. :)
Yes, in C++ a class method can only be overidden if it is marked virtual in Base class.
If your class is made for inheritance and your class method is meant to provide different behaviors for Base and derived then mark the method as virtual.
Good Read:
When to mark a function in C++ as a virtual?
Yes, you'd have to make all your methods virtual.
Java took the position that everything was fair game to override by default, and that prohibiting it required action. C++ and C# take the opposite view.
You can override a method in a base-class even without virtual.
Take this little program for example:
#include <iostream>
struct A
{
void m()
{ std::cout << "A\n"; }
virtual void n()
{ std::cout << "A\n"; }
};
struct B : public A
{
void m()
{ std::cout << "B\n"; }
virtual void n()
{ std::cout << "B\n"; }
};
int main()
{
A a;
a.m();
a.n();
B b;
b.m();
b.n();
A &c = b;
c.m();
c.n();
}
The output from the program is:
A
A
B
B
A
B
As you can see, the method B::m overrides the same method in A. But that only works when using an exact instance of B. In the third case, when using a reference to the base class you need virtual to make it work.
Programmers coming from languages where virtual functions are the default tend to be surprised that C++ has the reverse choice of defaults, i.e. non-virtual is the default. Note, however, that the contract of a [concrete] virtual function is a lot harder to document and test because there are actually two different contracts involved:
the contract of all overriding functions, i.e. what the function conceptually does
the contract of what the concrete function happens to do
Documenting only one of these won't really cut it because the other half isn't clear at all. This also means that you can't glance from a specific implementation what the actual contract is (assuming you are in the not so untypical situation that the documentation is provided by the source).

Categories