Java extend generically specified type - java

Is there anyway I could do something like this:
Class extends <T extends ClassB>
Can you have a class extend a class as long as that class extends the class that the generically specified class must extend?
What would be the syntax/structure for it?

No, that is not possible. I don't think it would make much sense either—when you use generics and specify a class this way, you only have the information from the class you specified.
For normal use (containers, for example), this makes sense because it lets you rely on a particular class or interface's methods while being able to ensure additional type safety. However, for extending a class, this would not really make much sense—since you can only rely on the methods of ClassB, it would be functionally identical to just doing Class extend ClassB.
For your idea to make much sense, you would need to be able to take the class you've defined and pass in a type to "extend". However, this would have many of the same pitfalls as multiple inheritance—what would you do if a method first defined in Class was also defined in the class you pass in to the generics, but not in ClassB? Not having multiple inheritance in Java was a design decision and having generics that work like that would go against that.
In short, something like this would either be like multiple inheritance or would be identical to normal inheritance.

I think that because of type erasure, you won't be able to do this. For instance, you can't even do this:
class A<T> {
class B extends T {
}
}

Related

Inheritance without "extends" keyword in Java

Is it possible to inherit a class without using extends keyword in Java ?
Yes. Every class extends Object, whether you add extends Object to the declaration or not.
There are also anonymous classes, such as
Foo foo = new Foo(){
// some method implemented in here.
};
which can extend a class without extends.
Yes, Each class extend the Object by default without declaration.
As has been said on this thread all classes extend from Object.
So it does exist, however this is not something which you can control without using the extends keyword. I don't think that you will ever need to, if you do maybe we should discuss that specific situation.

Class which extends abstract class

I have a problem, i have abstract class which implements interface, and one more class which extends this first abstract class, but i got an error it says that i my second class must inherit methods from interface, and i dont want that, i also can change it to abstract class too, but then i can't call constructor from that class in some third class, how can i fix this?
I searched for answer on internet but couldnt find it, and i dont understand abstract classes rly good so i can't solve it.Please help
(p.s. sorry for my english, it is really bad)
Edit:
I have an assignment where it is requiered that my second class needs to extend abstract class, and i am implementing interface because they also gave me main class in which they are making object from constructor in my second class and then they are using it with type of interface, i dont know if this makes any sense, code is pretty long, but i will give some lines: Here is my main class
(NationalTeam bulgaria = new NationalTeam("Bulgaria", Formation.F352, "Bulgaria");
nationalManager.setManagingTeam(bulgaria);) (bulgaria must be type of interface),
also here is my constructor from second class which extends abstract class:(public NationalTeam(String name,Formation formation,String country){
super(name,formation);
this.country=country;
})
Abstract class:Abstract classes may have abstract methods which means methods are methods without implementations.
when you are extending a abstract class A, methods of class A must be implemented by your subclass lets say B unless you make your child class B an anstract class.
You need to think how want to design the system not how compiler forces you.
If design says second class should be abstract then do it and then ultimately implement your abstract methods in your implementation.
On the other way, if second class is your implementation not abstract, the you have to provide implementation to make object of it
my second class must inherit methods from interface, and i dont want that
Really? Then why did you declare the interface in the first place? Why the abstract class needs to implement the interface?
Interfaces are supposed to be a higher level of abstraction. It is a contract between the client code and the library. It creates a interface between the client code and the library. It's like saying "I have the abilities to do the things the interface requires me to do". And you say you don't want to?
So there are two good ways and one bad way to fix this:
Good
Don't extend the abstract class. Because if you do, it probably does not make sense.
The abstract class don't extend the interface.
Bad (This is really really bad)
Add the methods in the interface and leave the body blank or return a random value. Again, don't do this if you don't have to.

Java : If A extends B and B extends Object, is that multiple inheritance

I just had an interview, and I was asked a question.
Interviewer - Does Java support multiple inheritance?
Me - No
Interviewer - Each class in Java extends class Object (except class Object) and if we externally extend one class like
Class A extends B{
// some code here
}
then you can say that class A extend class B and class Object, which means it is multiple inheritance. So how can you say Java does not support multiple inheritance?
Me - Actually class B extends class Object, so when you extend class B in class A then class A extends class Object indirectly. This is multi-level inheritance, not multiple inheritance.
But my answer did not satisfy him.
Is my answer correct? Or where am I wrong?
What actually happens internally?
My answer is correct?
Yes, mostly, and certainly in the context you describe. This is not multiple inheritance:
It's what you said it is, single inheritance with multiple levels.
This is multiple inheritance: Inheriting from two or more bases that don't have any "is a" relationship with each other; that would be inheriting from unrelated lines, or from lines that had previously diverged (in Java, since Object is always a base, it would be the latter):
(Image credits: http://yuml.me in "scruffy" mode)
Internally What happens actually?
Just what you said: There are multiple levels. When the compiler is resolving a member on an instance:
obj.member
...it looks to see if the type of obj (which in this case is a class, say ClassB) has member, either because it provides it directly or it has it through inheritance. At runtime, the JVM uses the member the object actually has.
The reason I said "mostly" above is that Java has interfaces, and as of Java 8 it has "default methods" on interfaces. This complicates things a bit, but your answer about levels is correct in the context of what you described the interviewer saying about Object, ClassA, and ClassB.
Interfaces have always made it possible, in Java, for something to have an "is a" relationship with two different types: A class type it inherits from, and any of several interface types it implements. Interfaces without default methods aren't multiple inheritance in a practical way (the class has to provide the implementation), but they did make it possible for a class to have multiple "is a" relationships from unrelated type trees. (I'm not an academic, it's possible an academic would argue that they provide multiple inheritance in an academic way.)
With Java 8, interfaces can provide default implementations of the methods they define, which really blurs the lines even at the practical level. Let's look at that a bit more deeply:
Say we have ClassA:
class ClassA {
void doSomething() {
// Code here
}
}
and Interface1:
interface Interface1 {
default void doSomethingElse() { // Requires Java 8
// Code here
}
}
and finally ClassB:
class ClassB extends ClassA implements Interface1 {
}
ClassB inherits the implementation of doSomething from ClassA. But it also gets the "default" version of doSomethingElse from Interface1. We didn't implement it in ClassB, but ClassB isn't abstract: It really has doSomethingElse. It gets it from the interface. I used the word "gets" rather than "inherits" there, but this looks a lot like inheriting the default method.
This is basically multiple-inheritance "light" (as in "light beer"). It does an end-run around the thornier problems with true multiple inheritance, like:
What should the type of super be? (Java 8's answer: ClassA)
What order do you run constructors in? (Java 8's answer: Single-lineage constructor chaining, interfaces don't have constructors.)
Do you run constructors that you inherit more than once, more than once? (Java 8's answer: You can't inherit constructors more than once, interfaces don't have them.)
What happens if you inherit multiple methods with the same signature? (Java 8's answer: If one of them is from the base class, that's the one that's used; a base class's implementation can override the default method of multiple interfaces. If you have multiple default methods with the same signature from different interfaces at compile-time, it's a compile-time error. If an interface has been changed without the class being recompiled and the situation arises at runtime, it's a runtime IncompatibleClassChangeError exception listing the conflicting default methods.)
you are correct
First of all, Object class is the super/base/parent class of every class including user-defined classes.
So even if we don't mention it explicitly, the user-defined classes extends Object class by default.
its like
class A
class B extends A
but compiler read it as
class A extends Object
class B extends A
proved
for more detail check this java documentation for inheritance
My answer is correct?
You are absolutely correct in saying that it is multi-level inheritance and not multiple inheritance.
Only the root of the hierarchy is Object, all classes don't individually extend Object.
A counter to the interviewer:
If all classes extend Object, then how many times constructor of Object will be called on A a = new A();
The answer is only once, and that will be for the root of the hierarchy.
Multiple inheritance and class Object
Yes, you are correct... as many others have pointed out. I just wanted to say that interviews are not only about technical knowledge, it is also about sticking to your guns. Some interviewers will question your answer, not because they want to know if you are sure of your convictions but also to test how well you can teach others and how well you handle an authoritative figure.
For the first point, if you can't teach others then you can't be a mentor. Nowadays it is crucial to hire someone who can coach junior developers.... because it makes sense economically.
For the second point, because they don't want you changing technical aspects just because your boss asked you to. If your boss asks you to remove all indexes from the database because they take up too much space, would you do it? Would you try to convince your boss otherwise? How?
Does java support multiple inheritance?
Yes for interfaces but not for classes.
The class and interface can implements many interfaces but extends only one class
Your answer is correct !
class Object //for illustration purpose
{
}
class B
{
}
class A extends B
{
}
When you create an object of class A, constructor chaining happens.
i.e. the constructor of class A calls super() implicitly and hence the constructor of class B is invoked, which then calls its super class implicitly which is the Object class.
In java, a class extends only a single class because the constructor of that class only call one super class constructor. This is not true in case of Interfaces since they do not have constructors.
Also when an object of class A is created, and assume that you have defined the constructors of both classes A and B, then constructor of class B is executed first and then the constructor of class A.
Your answer is perfectly alright. You can explain interms of multilevel inheritance support from Object class in java
Your answer is right, because java doesn't support multiple inheritance from classes. Java supports multiple inheritance from interfaces, and there is no any other inheritance. But you can use composition of classes, but that's another story.
What a dumb question.
Of course Java doesn't support multiple inheritance, and interfaces are not inherited.
Inheritance only happens via "extends", not via "implements". When you define a class implements several interfaces you are not saying it will be an extension of those interfaces, but it will have the same behavior, and behavior (at least in Java), doesn't define inheritance.
For Java to support multiple inheritance, it would need to support something like
public class MI extends Object, MyOtherClass
Which Java can't.
Well, maybe I wouldn't get the job for calling the interviewer's question dumb :)
Your answer is absolutely correct.
These types of questions asked just to check whether a candidate is conceptually strong or not.
Well the simplest and precise answer to this question is here:
"Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object."
Please refer this link
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The answer you gave is correct. The interviewer was wrong:
Internal process
if suppose Class A Doesn't extends any other class
then ---> Class B extends java.lang.Object
then ---> Class A extends B
then class A also inherited the property of java 'Object' class...
so,Java doesn't support multiple inheritance.
If you want to verify this process just generate 'javadoc' for your class A and verify the results.

Reference variables for behavior interface types in Java

I'm reading Head First Design Patterns and have some understanding in Java. It starts by encapsulating things that vary from your class and putting them in a seperate interface, as opposed to putting those functionality in the subclass. The example they give is an abstract Duck class that can quack or fly depending on the duck. They have an interface for quack and fly (QuackBehavior and FlyBehavior interfaces), and then implement those interfaces in other classes.
In the example, they have the abstract duck class as follows
public abstract class Duck {
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
.....
}
I guess what is new to me is having an instance variable that is of the interface type. I never learned that before but I'm assuming it's valid? I guess I'm more familiar with having an instance variable of a concrete class. Are there any rules about having instance variables of classes/interfaces like this? Thanks.
It is valid, and a common practice.
It doesn't matter what the instance variable is. It is even preferred to use interfaces where possible. For example always define variables of type List and not ArrayList
Otherwise how would you be able to have different behaviours? Now you can assign both LowFlyBehaviour and HighFlyBehaviour to the field, and thus different instance of Duck can have different flying behaviours. If the field was either of these concrete types, this would not be possible.
Yes, it's valid. The only rules the apply are the same the apply for any other type; namely that you can only assign something that implements the declared interface. You have probably seen or even used a similar syntax before without realizing it, like:
List<String> list = new ArrayList<String>();
Serializable s = new Object();
If you declare a field as an interface type, the filed will be able to hold any class that implements the interface.
It's a normal field.

Should we need to differentiate between Interface class and abstract class, in terms of naming convention?

Is that important to differentiate between Abstract class and interface class?
Abstract class is merely an interface class, with some concrete methods.
If the abstract class shares the same prefix "I" with Interface class, we can easily upgrade our interface class to abstract class, by introducing new logic etc.
UPDATE
The reason why I am asking this is, interface impose some limitation when the project grows.
For instance,
If one interface has been "implemented" by thousand classes, and at some point we need to introduce a few new methods in the base class, we will have to fix all the sub classes.
Abstract class provides flexibility in terms of functional expansion, as it can provide default implementation without affecting sub classes.
That's why I got the idea of using interface and abstract class interchangebly.
ICar car = new Merz(); // ICar can be interface or abstract class
However, when i think about it again, we still have to change all the sub classes, due to the fact that the class declaration forces us to use "extends" or "implements" at the very beginning.
So I think there is no option for doing polymorphism on abstract/interface class.
An "I" prefix isn't really the Java way. That's more C#.
For Java, I generally use this convention:
Interface: Builder
Abstract Class: AbstractBuilder
Concrete Class: BuilderImpl, DefaultBuilder, MyBuilder, etc
I think that agrees fairly well with Java standards (Map, AbstractMap, HashMap respectively).
As for replacing interfaces with abstract classes, that requires a refactor. I think it's a better idea to use interfaces for all method returns, data member types, local variable types and parameters. Abstract classes are (or should be) an implementation detail.
Going back to the Map example, that means everything is a Map. You can create your own Map subclass. The JDK provides you a helper class that does most of the boilerplate. If you declared members in terms of the abstract class, you'd be forced to use it and that isn't the best outcome.
No, you can't do that easily because you may be also inheriting from another class, and Java doesn't allow multiple inheritance from classes.
It is better to have a standard naming structure. In Java, I'm not sure you need to adopt the I prefix; I think it is the able suffix. Either way, adopt one, and make it consistent.
-- Edit
With abstract classes, my preference is for a Base suffix, but to each his own :)
An abstract class is very different from an interface on one particular thing.
A given class can implement any number of interfaces, but only extend one abstract class.
Hence, they should be treated very differently, but not in naming terms. Choose a short, descriptive name for the interfaces - you will see it a LOT again. For instance List is an interface, but ArrayList is the class.
I am working with Java the hole day and my colleagues and i are using
Interface : IDialog
Abstract: AbstractDialog
Class: DefaultDialog, WarningDialog
Abstract classes implements most common interface methods or most used util methods.
You do not have to extend from the Abstract class. You should extend from the Abstract class, if the implemented methods are usefull for the class you want to generated.
Otherwise you should implement the interface and implement the methods again.
You extend from 1 class only, so it makes no sence when you extend from the Abstract class if you only can use 50% of the methods.
Interfaces in Java end in 'able'. For Ex: Cloneable,Serialisable. So if possible you can choose a name that ends with 'able'. An abstract class which implements an interface should start with name 'abstract'. for ex: abstractLinkedList. The concrete class are not subjected to any such naming convention other than that they should make sense and start with a capital letter. I would suggest you to choose interface name that ends with 'able' or you can prefix I (last resort, not recommended for java but the default naming convention in MS languages like c#) to differeniate your interface from class implementation
# janetSmith,
well you can stick to cletus answer to use Car as interface name and CarImpl as the class that implements car interface. The only problem is a cursory look at 'Car' doesnt indicate whether it is an interface or a class unless one also looks at CarImpl. If you want, you can stick to prefixing interface names with 'I'. Its a trivial violation. Java practices suggests that. you can check it out here
Interface names should end with able when the class that implements it exhibits that behaviour.For Ex: if a sub class of car provided behaviour like move, park,etc. you can have interface names like moveable, parkable. this applies for interface names that are verbs without the suffix 'able'.
--EDIT : My opinion go for ICar.

Categories