Is "derived" in C++ the same thing as "extended" in Java? - java

As the title states: when I "derive" a class in CPP, that's pretty much the same thing as "extending" a class in Java, yes?

Yes. Since Java doesn't have multiple inheritance, it can be a bit more verbose with the language. Java's class D extends B is class D : public B in C++, but in C++ you can also have in­her­itances like struct D : B1, private B2, protected B3.
Similarly, in Java super refers to the (unique) base subobject, and understandably there is no com­par­able concept in C++ (you have to specify the base by name).
(Note that there's also implements in Java for dedicated interface classes. Since those have no mem­bers and only abstract functions, there's no need to refer to those interface bases from the derived (i.e. "implementing") class.)

Yes, they mean the same thing. Although, "derived" is not a keyword in C++ the way that extends is in Java, even though the C++ standard uses the word "Derived" to indicate the idea of a subclass. Inheritance in C++ is expressed using the : symbol, along with an optional access qualifier like public or private.
C++ inheritance is also slightly more complicated than Java inheritance, because multiple inheritance is supported, and as such virtual inheritance is also an option.

Related

Multiple Inheritance :Java vs C++

Recently ,after reading some articles in Programming Languages and Practice book ,it is mentioned that multiple interface inheritance in Java does not suffer from the same problems as multiple class inheritance in C++.
But I can't understand why this happens. How java is able to use multiple interface inheritance while in C++ implementation errors exists ??
Is there a way to replace multiple inheritance in C++ as to avoid implementation problems ??
For the last statement to be more specific ,lets say that we have:
class A {...};
class B : public A {...};
class C : public A {...};
class D : public B, public C {...};
Then class D inherits class B,C which both inherit class A. So if A had a field-variable then B,C would have the same variable name ,then what variable would D has (inherited from B or C) .To avoid this could we write the above code without multiple inheritance but with similar results?
The question is not a duplicate since it is not focused on what finally will be the inheritance in the example ,but to understand the difference between Java-C++ multiple inheritance(see the first question above) and also if there is a way suggested to overcome some multiple inheritance problems (like the above).
Java (unlike C++) does not allow multiple inheritance of state and, therefore, does not suffer from a diamond problem.
It allows multiple inheritance of type through interfaces (a class can implement multiple interfaces).
Starting with Java 8 there is also multiple inheritance of behavior through default methods in interfaces.
But I can't understand why this happens. How java is able to use multiple interface inheritance while in C++ implementation errors exists???
That is possible because Java does not allow multiple inheritance, but only multiple implementation from multiple interface.
Implementation is different than inheritance.
The general problem with multiple inheritance is (in short) that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick.
Since interface in java can only declare the signature of methods without implementing them, the problem does not exists if multiple interface are derived.
In conclusion, in order to avoid the problem Java forbids directly multiple inheritance, and allows only multiple implementation of interface.
Is there a way to replace multiple inheritance in c++ as to avoid implementation problems???
The first suggest I can give you is to avoid a design so complex.
Anyway the problem you've exposed in your question is very common and known as diamond problem.
C++ provides a solution in order to solve that problem with the usage of virtual inheritance.
Let an inheritance graph:
A
/ \
B C
\ /
D
This is the problem:
C++ by default follows each inheritance path separately, so a D object would actually contain two separate A objects, and uses of A's members have to be properly qualified.
And this is a briefly explanation about the virtual inheritance:
If the inheritance from A to B and the inheritance from A to C are both marked "virtual" (for example, "class B : virtual public A"), C++ takes special care to only create one A object, and uses of A's members work correctly. If virtual inheritance and nonvirtual inheritance are mixed, there is a single virtual A and a nonvirtual A for each nonvirtual inheritance path to A.
In short, with virtual inheritance you prevent the part class A is duplicate in the class D.
To avoid this could we write the above code without multiple inheritance but with similar results?
It follows a minimal, working example:
struct A {};
struct B {};
struct C {};
struct D {
operator A&() { return a; }
operator B&() { return b; }
operator C&() { return c; }
private:
A a;
B b;
C c;
};
void f(const B &b) {}
int main() {
D d;
f(d);
}
If you don't want to create an explicit hierarchy, but still you would like to use an instance of D where a reference to B is required, the solution above works just well.
It is based on composition instead of inheritance, as you can see.
It has some limits, of course, as an example you cannot cast a pointer to D to a pointer to B.
If it fits your requirements mostly depends on the real problem, so I cannot say.
Anyway, that's is a viable solution somehow similar to the inner class idiom, if you are interested in having further details.
The "multiple inheritance" in Java is no real multiple inheritance. Since Java can only create the diamond problem by using interfaces.
Interfaces are only a reference to an implemented method in the sub class, because an interface cannot implement a method.
So the child class cannot have parents with different implementions. It doesn't matter from which interface you inherit the method, since no implementation exists.
Edit: oh I forgot how Java destroyed the principle behind interfaces by introducing default methods...

How do I avoid code duplication without multiple inheritance (i.e. in java)?

(I'm a novice developer still learning best practices and java - any help/direction would be appreciated, thank you!)
Suppose I have the following situation:
ClassA extends abstract ClassB which extends abstract ClassC.
ClassD extends abstract ClassE which extends abstract ClassF
which extends abstract ClassC.
[ClassC is the parent class]
where ClassA and ClassD have a set of identical properties, getters, & setters.
I want to avoid that code duplication (properties,getters,setters). I also want to avoid writing different methods doSomething(ClassA class, ...) and doSomething(ClassD class, ...) that are identical in all but the argument type.
If these two classes inherited directly from ClassC, I'd have them extend a class that had all the getters and setters and properties, and pass that type into the method doSomething(..). Since ClassA and ClassD can't extend multiple classes, what's the best way to deal with this situation?
First of all, let me say that it is very good when a (by their own admission) novice developer is concerned about issues of this kind. Most developers refrain from thinking, and just write lots and lots of mindless code because this is the path that they know will work, no thinking necessary. (And having to maintain all that code never seems to be much of a problem because... it lies so far in the future!)
Composition
The approach that most Java shops follow is to avoid inheritance, because it is too complicated, and use composition instead, which also results in lots and lots of mindless code having to be written. More often than not, this is done due to a misinterpretation of the advice that said "favor composition over inheritance" as if it said "use only composition, never use inheritance".
I do not know exactly what you are working with, so I cannot advice you to drop what you are doing and use composition instead. I will just assume you have your reasons for using inheritance, so, I will not write more about composition here; if you are interested to learn more about composition, the term "composition vs. inheritance" can easily be googled.
Interface inheritance
Judging by the class structure you described, you seem to be in the typical kind of situation that would greatly benefit from the use of interfaces: In Java, a class cannot extend multiple classes, but it can implement multiple interfaces.
If two interfaces both define a method like reticulate( Spline s ), and a class implements both of those interfaces, then it can provide a single implementation of reticulate(), and it will satisfy both interfaces. (The disadvantage of this is that if you want your class to provide a different implementation of reticulate() for each interface, you are stuck; it cannot be done.)
Furthermore, Java supports default methods in interfaces, which means that a certain part of the functionality you need to offer can be coded straight into the interfaces, so that implementing classes inherit this functionality from the interface and therefore do not have to re-implement it.
I'm not sure if I understood your problem correctly but I'll give it a try. Instead of multiple abstract classes, create multiple interfaces. Then create a class that implements both interfaces. Java allows implementing multiple interfaces but not extending from multiple classes.
Seems to me that it might be useful to have a ClassAD, that extends ClassC and contains the methods common to ClassA and ClassD.
Another option is to create an interface InterfaceAD and have ClassA and ClassD implement it. Use the interface as a parameter to the functions, like doSomething(InterfaceAD i)
you can do like
class M
class A extends B
inherit B's stuff
class D extends E
inherit E's stuff
A b = new A();
D d = new D();
// or use anonymous classes
M has access to everything in A and D,
therefore M has access to A and D inheritable assets.
Now add you common method in C class
You should really discuss the abstract classes here. How are you going to test A, B, and C, D, E, and F?
That will include a lot of duplicate testcases for any method implemented by C (since it is also used by all other classes), etc.
As has been said, really discuss composition over inheritance. A might have a C, and pass through methods. It might also have a Q, and so will D.
Both D and A can then implement the same interface (possibly also implemented by Q, although that would probably make it confusing)
Be aware, I'm not a fan of abstract classes, and prefer to use composition and/or strategies instead.

Analogy/Equivalence in C++ and Java

Two things:
1.Are Nested Classes in Java like Composition in C++?
2.Are Virtual functions in C++ equivalent to Function Overriding in Java?
Nested classes in Java come in two flavors: Inner Classes and Static Nested Classes.
There is no direct equivalent of an Inner Class in C++. If you want it, you need to do it manually, giving the "Inner Class" a pointer back to the outer class (either in every method as an argument, or stored within the "Inner Class").
A static nested class in Java is similar to declaring a class within a class in C++.
Composition in C++ is when an actual value of the composed class is stored within another class. There are no class-value-types in Java, all Java class types are references, so there is no direct equivalent in Java. Java "composition" is going to store references to the "sub-objects": this can be done in C++ via references, pointers or smart pointers.
C++ virtual methods are similar to non-final non-static methods in Java. C++ non-virtual non-static methods have no real equivalent in Java (final methods are approximately equivalent, but more similar to virtual final methods in C++). You can override a virtual function in C++ in ways somewhat similar to how you override a non-static non-final function in Java: for example, they both support covariant return types (they may disagree about what is covariant, however). Some of the details are going to be different.
static methods in Java and C++ are similar.
(I am a C++ programmer, my knowledge of Java is almost entirely a matter of contrast: trust my statements about C++ far more than my statements about Java.)
Both Java and C++ support nested classes and composition, and as per Thomas Matthews' comment: "They are treated the same in both languages."
In Java, all non-static methods are virtual by default (you can use final to make them non-virtual). In C++ you have to explicitly mark them virtual to be able to override them.
Composition is a design term, nesting classes is a language mechanism (which may be used to implement composition). As Thomas Matthews mentioned in his comment, both languages support nested classes.
Non-static methods in Java behave polimorphically by default, i.e. unlike in C++ you don't use the virtual keyword to make a method virtual. This question has some good answers about how virtual methods work behind the scenes: Java - Virtual Methods
1.) Java and C++ support nested classes. After all, in java a class can have an instance in another class's member data.
Composition is just having a wrapper class for other classes.
Like this example from wikipedia
class Pond{
private:
std::vector<ducks*> myDucks;
}
2.) Virtual functions are functions that are defined in base classes in C++ for classes that inherit the parent class to define. virtual is required to overload the function in classes that inherit the parent class.
Ad. 2. The method / virtual function in C ++ is:
Method with the default implementation;
It can be override in a derived class but it does not have to;
It can not be static, it is used to obtain polymorphism;
We can refer to the method by the base type for
polymorphism;
Looking at the above, an analogous method for Java would be a method with the modifier "default" in the interface, available from version 8.
example:
public interface Foo {
default String bar() {
return "Foo.bar";
}
}

Is possible to support multiple inheritance through virtual?

I know that Java does not have any ability to support Multiple Inheritance. For an example, class C inherits all the properties from class A and class B then the compiler gets confused which method should be called which is defined in A and B. So, C++ supports multiple Inheritance and Java does not support.
I know that by using Interface can achieve this Multiple Inheritance in Java.
My doubt is, whats that Diamond problem and how could be solved in Java?
For an example, consider multiple classes such as A, B, C, D. Class B and Class C inherits the properties from Class A and class D inherits the properties from both class B and Class C. This is called as "Diamond problem".
How can we solve this Diamond problem in Java and when does this Diamond problem may occur exactly in coding?
I also referred that in C++ by using Virtual can achieve this Multiple Inheritance concept. And, Java is built and designed for simplicity !
What is that actual meaning of Virtual in C++ and how could be used in Java? Is it possible to achieve multiple Inheritance through Virtual?
I am Java Beginner and very sorry for this kinda question. But, I believe that can learn from my mistakes!
There is no concept of multiple inheritance in Java. Implementing multiple interfaces is possible, but this is not multiple inheritance.
Because there's no multiple inheritance, the "diamond problem" that arises in languages that do have multiple inheritance does not arise in Java. So there is no virtual keyword in Java - there's no need for it.
The designers of Java decided that the number of cases in which multiple inheritance is actually useful is so small that it wasn't worth including in the language. In approximately 15 years of programming Java, I have only once encountered a business problem in which C++-style multiple inheritance would have been useful. So I'm happy to say they were right.
If you want multiple 'inheritance', you need to implement multiple interfaces. Each interface declares abstract methods that the implementing class needs to provide definition for.
public class MyClass implements interface1, interface2, interface3{
// provide a definition to the abstract methods of interface
}
The 'diamond' problem in C++ is when a class inherits from two classes , both of whom have methods from a common grand parent. In Java, there is no diamond problem because you can never extend two classes; just one class and many interfaces.
You are combining far too many questions. I recommend that you split your post into separate questions.

Java - what is a a prototype?

In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods

Categories

Resources