Class which extends abstract class - java

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.

Related

Is it useful to have an abstract class without Abstract methods? [duplicate]

I am now studying a java and I'm at the part of Abstract.
I read sorta strange part to me that there is an abstract class
which does not include any abstarct method.
Why do they use this kind of class?
To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.
A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.
Yes, we can have abstract class without any abstract method.
Best example of abstract class without any abstract method is HttpServlet
If this class extends another abstract class and don't have implementation of inherited abstract methods.
This class contains some common logic for all its inheritors, but itself does not represent usable entity (in terms of particular application)
These type of classes are used for a implement a general logic which can be implemented by other classes. Making it abstract prevents from instantiating it. But other classes can inherit the class and its methods.
Say you have a set of related classes, but no related (shared) code, yet. If we make all of these classes extend a base class with no abstract methods, that then if we wan't all of these classes to have an identical method/feature in the future, that can be done in one shot by putting it in the base class. So code is not repeated and it reflects in all child classes by including it in just one place.
Another example for having such class is when you implement creation helpers. These classes are used to ease the client in the creation of objects, which are related in topic but decoupled depending on the need. By nature, the methods of this creator classes are all static and they can be seen as utility classes as well.Obviously, instatntation of this classes is futile and hence the abstractkeyword.
To mention a recent example I met was the Sftpclass from org.springframework.integration.dsl.sftp which is basically an easy way to require objects (e.g: adapters, gateways) from the sftp api.
I develop a abstract class to prevent instantiation of that class and use it only as a base class. because, These type of classes are used for a implement a general logic which can be implemented by other classes. Sometimes, I have a default implementation for every method in abstract class. In the manner, it doesn't force the sub-class to override all of method, but also it implement everyone that is need.It means implicitly you have to override at least one method to make scene using this abstract class.
I can't think of any good reason to use it. It could be used as "marker" but an interface would be a better choice.
Abstract class without abstract method means you can create object of that abstract class.
See my Example.
abstract class Example{
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo
{
public static void main(String[] args)
{
Example ob = new Example(){};
ob.display();
}
}
If you write one abstract method inside abstract class then it will not compile.
Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.

Technical difference between abstract class and interface [duplicate]

This question already has answers here:
What is the difference between an interface and abstract class?
(38 answers)
Closed 8 years ago.
Conceptually I know the difference between abstract class and interface. But wondering about the technical difference between these two. Why Sun made this interface term even though I can have fully abstract class and make my work done.
Read here http://javarevisited.blogspot.kr/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html
Difference between abstract class and interface in Java
Abstract Class vs Interface in Java and When to use them over otherWhile deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java.
1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language.
2) Java interface can extend multiple interface also Java class can implement multiple interfaces, Which means interface can provide more polymorphism support than abstract class . By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where class extends Canvas and implements CommandListener to provide both graphic and event-handling functionality..
3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.
I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find all those syntactical differences.
Read more: http://javarevisited.blogspot.com/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html#ixzz31l59K92Z
you are free to choose interface or abstract class in the above scenario
but keep below things in mind
if you made a fully abstract class then
your subclass will extend one class to implement that behaviour and
its not eligible to extend any other class as multiple inheritance is not supported in java.
see without interface we cant achieve multiple inheritance.
Now if we approach interface instead of fully abstract class
then class can implement it and still eligable for extension of one more class.
so choose fully abstract class in your design if your sub classes can never need to extend any other class.
if sub classes need to extend some classes later (usually its how we need in application) then choose interface.
You write a java program with interfaces, abstract class and concrete class but do not mention any constructor, compile it and see byte codes in .class files. You would see as expected abstract class and concrete classes have default constructor added by compiler where as interfaces do not get constructor added to it by compiler. This should help you understand technical differences as I believe you know other differences.
I might receive downvotes for this answer :) . Consider this scenario.
public class TestClass{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish f = new Fish();
f.walk();
}
}
abstract class Animal {
protected void walk() {
System.out.println("walking");
}
}
class Fish extends Animal {
}
O/ P : walking
Technically a fish can't walk. Still since it extends the Animal class, it "can" walk which is wrong from a design perspective(even though Fish doesn't implement walk(), it can still call it).. If Animal were to be an Interface, then Fish must implement the method walk() which it won't / shouldn't. So, you will be forced to relook at the design.
Because you can have a class implement 2 interfaces, but you can't have a class implement (or extend) 2 abstract classes.
An abstract class can have some implementation code and instance variables. An interface has only method signatures and static variable definitions, no implementation code.
Further, if you implement an interface you must include implementation code for all of the methods defined in the interface.

Why do we create an abstract class even though all the methods of that class are defined?

Why do we create abstract classes even though all methods of that class are already defined?
If the answer is to stop the programmer from creating an object of that class, couldn't we achieve the same thing by using a private constructor?
A class being abstract only prevents that particular class from being instantiated. Child classes may still allow instantiation.
A class with no non-private constructors prevents subclassing as well as public instantiation.
From the above you can see that these two things serve two different purposes. A class may have either—or even both properties.
The idea of the Abstract class is a common base for a number of other classes..
Think of "Animals".. You cannot create something called 'Animal'..
You have Cats and Dogs and Rabbits that 'Are' animals.
You have a abstract class called "Animal" and then you have a class called Cat that extends Animal, or Dog that extends Animal... but you do not instantiate the class "Animal" directly as its only a common base.
The design pattern of creating a class as abstract even though all methods are defined is used when the abstract class has "do nothing" or exception-throwing implementations of the methods.
We can see this in action in the HttpServlet class, which has implementations for each of the web methods (doGet(), doPost(), doPut() and doDelete()) that throw a ServletException and which a subclass must override if they want a class that does something useful for a particular web method.
Any web methods not overridden with a working implementation will explode by default.
Abstract classes show that this class in itself will not be used independently and some other concrete classes should extend it to make complete sense.
While preventing using private constructor will inhabit subclassing.
Abstract classes with no abstract methods maybe a mistake of the developer.
In Abstract class you can define the constants which are common to many class
If you have a class which only contains static methods, the you can do it abstract, as there's no need of instantiating it. I can think about utility or helper classes at least.
Specifically regarding the use of abstract vs. hiding the constructor: The abstract keyword more clearly states the architectural intent of the programmer. It's better practice.
The fact that they've provided default implementations of all the methods is a separate question.

Abstraction clarification. Java

Hello I have just been learning about abstraction and was looking for a bit of clarification.
1 - Is the only reason for using an abstract method to be able to pass static type checking without actually having to implement the method? Is there any other reason why someone would want to make a method abstract?
2 - If you made an abstract method and had some code in it, how would you "add to" that code in the sub class implementation. Would you just carry on typing? I have only seen empty abstract methods in examples.
Thanks and sorry if these questions are a bit basic.
Abstract classes, like interfaces, allow you to specify a kind of contract between you (your class) and your user (the user of your class). The difference to interface is that you can also provide some behaviour, that is you can implement some methods and leave other methods empty, that is abstract.
An abstract method is always empty - that's what it means to be abstract. Subtypes of an abstract class can change behaviour of a method implemented in the abstract parent by implementing the method themselves. They can reuse the parent's code by calling the parent's method first - like you do with constructors.
At 1: abstract methods are a way to suggest to a programmer that extends your code, that "there should be a method like this implemented in your code". This may be used to pre-design interfaces in some bigger systems, for example.
At 2: yes. When implementing sub-classes of some abstract classes you are not restricted only to the methods and fields of your "parent" class.
1 - abstract classes are meant to be extended by a regular class. so by having abstract methods, it forces the implementation of the abstract method in the class extending the abstract class, however, it also gives control to the programmer on how it should be implemented. lets say the class Lion and class Dog both extend the class Animal. lets say Animal class has run() method. both lion and dog can run but the way they run, how fast they run is different. thus, by making run() abstract, you can define run() specifically to Lion and Dog classes.
2 - abstract methods can't have a method body or any code inside.
For example: abstract void run();
notice there are no starting and closing braces after run();

abstract classes ,constructor and interface

I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
A class can implement multiple interfaces, but it cannot implement multiple abstract classes.
Interface itself cannot do anything. It just defines kind of contract between the class(es) that provide some functionality and the caller.
Abstract class is the class that defined as abstract. If class has at least one abstract method (i.e. method without implementation) it must be defined as abstract. But abstract class can contain implementations as well.
Interface cannot contain implementation. Only abstract methods and constants (static final fields).
Class can implement several interfaces and extend only one class (including abstract class).
I hope this helps.
Abstract class can also contain function implementation rather than just defining the functions that have to be implemented by inheriting classes
Abstract classes are partially implemented classes, that will be extended by concrete classes(non-abstract), to be implemented.
Example:
This example does not mean that the sub classes must implement those methods(as it happens when implementing an interface). You can declare a subclass abstract, and the implementation will be done later by annother sub-sub-class. (For example: Boat can have subclasses "SpeedBoat" and FisshingBoat, and the may implement honk() in different ways)
The interface are the eyes of class to the outside world. What classes can do is declared in the interface, but implemented in the class.
A class can implement many interfaces, but can extend only one class.
See this little example of interfaces:
As you can see when we use interfaces we can have a lot of flexibility. Some Enemies can do things that some Heroes can do too(DarkKnight can throw arrows).
I hope you now feel the difference between the abstract classes and interfaces.
Remember this about interfaces and Abstract classes:
Interfaces dont have variables, just non implemented methods(abstract methods implicitly)
Classes that implement interfaces must have all the methods of the interface in its body
One class can extend only one class but implement more than one interface
If a class has an abstract method, it must bee declared as abstract.
Abstract classes can implement interfaces
Interfaces can extend other interfaces(more than one)
I dont know if i forget something, i hope this information helps.
An abstract class can everything that a Interface can do. However inverse of this is not correct.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.
We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed
Interface and abstract class almost both are same the major difference is using interface we are not able to define the body of the method but using abstract class we can define the body of the method inside the abstract class or while implementing it.
e.g
Interface abc()
{
string xyz();
}
abstract abc()
{
string xyz()
{
// define body
}
}
or
abstract abc()
{
string xyz();
}
An abstract class is a class - it defines all or part of an implementation of some behaviour for a class of objects, but with some extension points for concrete subclasses to provide.
An interface is a type - it defines the set of operations which are provided by any class implementing the interface.
You're almost asking whether there is anything that a candidate can do that the job description can't. Creating an abstract class says 'here is a template for some implementation'. Creating an interface says 'I expect an object to provide these capabilities'. You can use virtual methods in an abstract class to implement some aspects of a type, but the intention is different.

Categories