Trouble with implementing abstract super class Java - java

I'm working on an assignment where I'm trying to implement a class that extends an abstract super class, but by using
public class B extends A{}
However, that gives me the error that type B must implement the abstract method A.act, is there another way in which I can do this without using extends?
Using:
public abstract class B extends A{}
Gives me a different error on another part of the assignment that should be correct.
What should I do? Thanks for the help.

In order for B to instantiated by the JVM, it must not be abstract. A abstract class is an idea or suggest of how a class might work, with some (or all) of the functionality needing to implemented by those classes that extended it.
For B to be instantiated, it must implement all the abstract methods of A.
To solve your problem, you must provide an implementation of the methods that A has marked as abstract...
public abstract class A {
public abstract void implementMe();
}
public class B extends A {
public void implementMe() {
// Your implementation
}
}
The reason for much of this is it allows you to pass B to methods and classes that use A and also change the way in which A works. This is part of polymorphism, where one instance of object can act as its parent (B acting like it's A)
I don't know if it will help, but you could have a read of Abstract classes
and methods

don't declare method act in abstract class A as abstract method if you do not want to provide implemenation of act in B. But that may not be a right choice depending upon what you are trying to achieve. In second case, when abstract class extends another abstract class, use "implement" instead of "extends". hope it helps

Related

Why mark class abstract when there is no abstract method

I am little confused about abstract class in java. I know that whenever there is an abstract method in the class compiler force developer to mark class abstract. But even we don't have any abstract method in the class we still mark the whole class as abstract. I am not getting the point why we can do this. what is the purpose to allow developer to mark class abstract when there is no abstract method. One can say that reason is that we don't want to create instance of that class. If that the reason then marking constructor of the class private is more suitable rather than marking class abstract.
There is a very useful reason for having an abstract class without abstract methods: Providing default implementations for overridable methods.
There are several perfect examples in the JDK itself. Look - for example - at a WindowAdapter. It implements the WindowListener interface (among others), but provides empty not-doing-anything method implementations. In most cases you want to register a window listener that only overrides one or two of the interface methods. Then your own class simply extends WindowAdapter instead of implementing WindowListener.
Note, that with Java 8 default methods in interfaces this reason does not hold anymore, and in fact abstract classes without abstract methods do not make sense anymore.
I think it's to allow subclasses to be created but not the main class.
I guess your class has method stubs in it, otherwise tyere would be no reason not to instantiate it. It is generally better to use abstract methods for this.
For restricting the class to be instantiated.. Example HttpServlet class.. it is defined abstract but has no abstract methods.. We can use these methods in the subclasses but creating the class httpservlet itself is useless.. thats the reason i think..
HTH!
As stated, this can be to prevent instantiation. I strongly prefer private or protected constructors over this as I feel they communicate the intent more clearly.
Also, in a class hierarchy, if class A is abstract and contains an abstract method, that method does not need to be defined in a class B which extends class A. In this case, class B is marked as abstract and has no abstract members.
To prevent instantiation of a class and use it as a base class. For example, HttpServlet class, an example of template method design pattern where each method already has a behaviour defined. The child class is free to override one or more of them instead of all of them.
One can say that reason is that we don't want to create instance of
that class. If that the reason then marking constructor of the class
private is more suitable rather than marking class abstract.
No it is not at all suitable
This below example will clear your doubts , If you use private constructor , Not only your Object creation is blocked but also you can not even create a subclass of the Parent class
class ParentClass{
private ParentClass(){
}
}
class Subclass extends ParentClass{
static{
System.out.println("Hello");
}
}
You will get compile time error saying
error: ParentClass() has private access in ParentClass
But Marking a class as abstract will block Object creation but will not block Inheritence in java
Update
As you asked in comments that you can make it protected but then your class can be easily instantiated , because protected member can be accessed from the same class as well as in SubClass in same package as well as in a sub class in another package .

Class extending more than one class Java?

I know that a class can implement more than one interface, but is it possible to extend more than one class? For example I want my class to extend both TransformGroup and a class I created. Is this possible in Java? Both statements class X extends TransformGroup extends Y and class X extends TransformGroup, Y receive an error. And if it is not possible, why? TransformGroup extends Group but I guess it also extends Node since it inherits fields from Node and it can be passed where a Node object is required. Also, like all classes in Java, they extend Object class. So why wouldn't it be possible to extend with more than one class?
TransformGroup inheritance
So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super class, while in the first approach the super class is ambiguous.
Consider if both Animal and Canine had a method drink(). Under the first scenario which parent method would be called if we called Dog.drink()? Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it.
No it is not possible in java (Maybe in java 8 it will be avilable). Except the case when you extend in a tree.
For example:
class A
class B extends A
class C extends B
In Java multiple inheritance is not permitted for implementations (classes) only for interfaces:
interface A extends B, C
E.g. MouseInputListener extends MouseListener and MouseMotionListener
And, of course, a class can implement several interfaces:
class X implements A, F
Multiple inheritance is not possible with class, you can achieve it with the help of interface but not with class. It is by design of java language. Look a comment by James gosling.
by James Gosling in February 1995 gives an idea on why multiple
inheritance is not supported in Java.
JAVA omits many rarely used, poorly understood, confusing features of
C++ that in our experience bring more grief than beneļ¬t. This
primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic
coercions.
There is no concept of multiple inheritance in Java. Only multiple interfaces can be implemented.
Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.
Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.
class A extends Object
class B extends A
java can not support multiple inheritence.but u can do this in this way
class X
{
}
class Y extends X
{
}
class Z extends Y{
}
Most of the answers given seem to assume that all the classes we are looking to inherit from are defined by us.
But what if one of the classes is not defined by us, i.e. we cannot change what one of those classes inherits from and therefore cannot make use of the accepted answer, what happens then?
Well the answer depends on if we have at least one of the classes having been defined by us. i.e. there exists a class A among the list of classes we would like to inherit from, where A is created by us.
In addition to the already accepted answer, I propose 3 more instances of this multiple inheritance problem and possible solutions to each.
Inheritance type 1
Ok say you want a class C to extend classes, A and B, where B is a class defined somewhere else, but A is defined by us. What we can do with this is to turn A into an interface then, class C can implement A while extending B.
class A {}
class B {} // Some external class
class C {}
Turns into
interface A {}
class AImpl implements A {}
class B {} // Some external class
class C extends B implements A
Inheritance type 2
Now say you have more than two classes to inherit from, well the same idea still holds - all but one of the classes has to be defined by us. So say we want class A to inherit from the following classes, B, C, ... X where X is a class which is external to us, i.e. defined somewhere else. We apply the same idea of turning all the other classes but the last into an interface then we can have:
interface B {}
class BImpl implements B {}
interface C {}
class CImpl implements C {}
...
class X {}
class A extends X implements B, C, ...
Inheritance type 3
Finally, there is also the case where you have just a bunch of classes to inherit from, but none of them are defined by you. This is a bit trickier, but it is doable by making use of delegation. Delegation allows a class A to pretend to be some other class B but any calls on A to some public method defined in B, actually delegates that call to an object of type B and the result is returned. This makes class A what I would call a Fat class
How does this help?
Well it's simple. You create an interface which specifies the public methods within the external classes which you would like to make use of, as well as methods within the new class you are creating, then you have your new class implement that interface. That may have sounded confusing, so let me explain better.
Initially we have the following external classes B, C, D, ..., X, and we want our new class A to inherit from all those classes.
class B {
public void foo() {}
}
class C {
public void bar() {}
}
class D {
public void fooFoo() {}
}
...
class X {
public String fooBar() {}
}
Next we create an interface A which exposes the public methods that were previously in class A as well as the public methods from the above classes
interface A {
void doSomething(); // previously defined in A
String fooBar(); // from class X
void fooFoo(); // from class D
void bar(); // from class C
void foo(); // from class B
}
Finally, we create a class AImpl which implements the interface A.
class AImpl implements A {
// It needs instances of the other classes, so those should be
// part of the constructor
public AImpl(B b, C c, D d, X x) {}
... // define the methods within the interface
}
And there you have it! This is sort of pseudo-inheritance because an object of type A is not a strict descendant of any of the external classes we started with but rather exposes an interface which defines the same methods as in those classes.
You might ask, why we didn't just create a class that defines the methods we would like to make use of, rather than defining an interface. i.e. why didn't we just have a class A which contains the public methods from the classes we would like to inherit from? This is done in order to reduce coupling. We don't want to have classes that use A to have to depend too much on class A (because classes tend to change a lot), but rather to rely on the promise given within the interface A.
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1(); - here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
Hello please note like real work.
Children can not have two mother
So in java, subclass can not have two parent class.

one abstract class(superclass),two subclass, one implementation in one subclass. is it legal?

Is it really necessary to implement all the methods to a subclass(inherited from a abstract class), if there is another subclass of that abstract class has already implemented those abstract methods?
abstract class A {
abstract void method();
abstract void anothermethod();
}
class B extends A {
void method() {}
void anothermethod() {}
}
class C extends A { // is this class definition is legal?
void sample() {}
}
Only if you mark C as an abstract class. Therefore passing on its implementation responsibilities to it's subclasses.
Another option would be to have C extend B, and therefore B would contain the implementation demanded of A by its subclasses.
No, it's not legal. You've got a concrete class (C is not declared abstract) extending an abstract class, but without providing implementations for its methods. It's not really clear why you think this should or could be legal - and you should consider whether this has wider ramifications for your understanding of inheritance in general than just this specific case.
C is entirely separate from B. They could have entirely different state - for example, B might implement method() using some state which is only present in an instance of B. It's important to understand that an instance of C is not an instance of B.
If you want it to inherit its behaviour, you should make C subclass B instead of A.
No. Class C will be abstract in this case, too.
What about class C extends B?
Thats absolutely illegal unless you make the class "C" abstract as IronBlossom suggested or implements all the abstract method of class "A"in class "C".

Inheritance problem Low level Design approach

Suppose I have class hierarchy like the one shown in picture. Suppose I need to include a method doThis() that would have different implementation in classes C and D. But the class B need not implement this method.
Should I declare the contract in Class A and provide an empty implementation in class B or have another abstract class X which extends A and is being extended by C and D?
Thanks
Do not put it into class A. Use an interface that is implemented by those that need it.
If only sub-classes of A will use the method:
Make another abstract class that extend A and adds the method.
If you intend to have that method implemented in different class types:
Make an interface that declares the method, and then C,D should implement that interface as well.
Make an interface called "doable". let your classes C and D implement this.
public interface Doable {
public void doThis();
}
public class D implements Doable { /*implementations*/ }
public class C implements Doable { /*implementations*/ }
Do not put it in A if you can avoid it.
The best solution can not be determined from the information you have given us. It depends on the context and meaning of the classes and methods.

Why an interface can not implement another interface?

What I mean is:
interface B {...}
interface A extends B {...} // allowed
interface A implements B {...} // not allowed
I googled it and I found this:
implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
However, interface is an 100% abstract class, and an abstract class can implement interfaces (100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
In details,
interface A {
void methodA();
}
abstract class B implements A {} // we may not implement methodA() but allowed
class C extends B {
void methodA(){}
}
interface B implements A {} // not allowed.
//however, interface B = %100 abstract class B
implements means implementation, when interface is meant to declare just to provide interface not for implementation.
A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.
implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.
extends means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.
On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
However, interface is 100% abstract class and abstract class can
implements interface(100% abstract class) without implement its
methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
Hope this will help you a little what I have learned in oops (core java) during my college.
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.
Here is an example below, this is my understanding and what I have learnt in oops.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below
public interface Dog
{
public boolean Barks();
public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
public boolean Barks{
// method definition here
}
public boolean isGoldenRetriever{
// method definition here
}
}
and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

Categories

Resources