Which use for non-inherited abstract classes? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What does good practice tells us about non-inherited abstract classes ?
Is there a reason for them to exist in a program not aiming at providing an API ? Could it make sense to systematically turn such classes into non-abstract classes? If so in which cases ?

Well, abstract keyword forbids inctances creation (in order to create an instance one has to inherit from abstract class), however, abstract classes can have static methods e.g.
// abstract: there's no sence in creating an instance of this class
abstract class MathLibrary {
// private: there's no sence in inheriting from this class
private MathLibrary() {}
// Gamma function
public static double gamma(double value) { ... }
...
}
please note, that when in Java abstract final class is not allowed, in C# abstract sealed class is static class:
// C# static == abstract sealed
public static class MathLibrary {
// Gamma function
public static double Gamma(double value) { ... }
...
}

Short answer : The one and only reason for creating Abstract Classes is to inherit them.
Note : This is why we can't creat a class or method using a combinaison of the abstract and final keywords because a final class cannot be subclassed.

IMHO, they have no use, since they can only be used when inherited.
Neither would it be of use to transform them into non-abstract classes, since ... You're not using them.
An abstract class is a blueprint to build on, it shouldn't be able to be instantiated. Maybe somewhere there is an anonymous class extending it?
But being there, means they can be used in the future, so deleting them might not be the good idea you're after, either.

well, practically for me there is no reason to do so.
Any case I can imagine right now it would be better to use other ways/design-patterns like singleton, utility, etc..
Maybe you can use them as template to inherit during runtime by reflection etc... (but this would be inheritance as well).

"non-inherited abstract classes"
That completely defeats the whole point of abstract classes. The idea of abstract classes is to be a blue print for OTHER CLASSES to be build on.
For example, you can build a Car abstract class, then inherit from that class to create diffrent Car Brands classes that automatically have everything that Car has, but each Brand is different. This way you avoid writing all the instance variables and methods that you could have written in Car in each Car Brand.
Also keep in mind, that you cannot create a Car instance, because its impossible for a a car not to have a brand, so it make sense to make Car abstract.

Related

Static methods in abstract class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I recently learned from a video that it's a good practice to turn a Java class into abstract if all of its methods are static for performance reasons.
Can anyone explain why this is the case?
This is likely to prevent people from creating instances of the class. Java code is expected to create lots of objects that are useful for a short time and get garbage-collected, so it is hard to say this is any kind of substantial performance win. It seems more like a way to communicate the intention behind a class.
Another alternative is, instead of making the class abstract, make the class final. This is the approach taken in JDK code, for instance, java.lang.Math:
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
With either of these approaches you should give the class a private constructor. That prevents anyone from instantiating it and makes it clear the class's purpose is to provide a home for the static methods. The downside here is code coverage tools tend to report the constructor as uncovered.
A third alternative, as of Java 8, is to put the static methods on an interface. Any methods with an implementation that aren't default get assumed to be static methods. The advantage of that approach is there is no constructor to make private, and the code coverage tools will be happy.
With an abstract class (but without the private constructor), or an interface, there is also the possibility of extending or implementing the type to make all the static methods available without static imports. See this link for an example. With the java.lang.Math approach that isn't an option.
You don't have to make it an abstract if it has static methods. if you make it an abstract class then no one can instantiate this class.
on the other hand, you can declare a class with a private constructor, so no one, not even a subclass, can instantiate an instance of your class.
public class A
{
private A()
{
throw new RuntimeException("Instantiation of MyUtility is not
allowed!");
}
public static void aMethod()
{
// Your method here.
}
}

Is exposing static methods in abstract classes considered good or bad practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?
I've produced a simple example program to illustrate what I mean.
public abstract class StaticMethodsInAbstractClassesStudy {
public static int adder(int a, int b){
return a + b;
}
}
public class StaticMethodsInClassesStudy {
public static void main(String [] args){
System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));
}
}
When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.
I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.
Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?
It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.
I agree with you that a abstract class make us think of something to not use until it will be instantiated.
It's allowed and useful to insert some support methods inside an abstract class without enforce the developer to implement that class.
Also in an Interface you can put static methods, and you can use them without implementing that interface.

Do I need to override a method that is implemented in an abstract class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an abstract superclass. Some of the methods have implementation in the abstract class. In my subclass would i need to override the implemented method. The method in the subclass does exactly the same as superclass.
public abstract class vehicle {
public int getNumber() {
return 5;
}
}
public class car {
public int getNumber() {
return super.getNumber();
}
}
So my question is, do i need to override the method and include a super call? Or can i just leave it in the super class and not implement it at all in the subclass?
No, you do not. You can just leave it in the super (parent) class and not implement it at all.
The Reason
Basically the idea behind an abstract class (very briefly) is that you can write down common implementations that all the concrete classes derived from the abstract class once, and then not have to override or rewrite them again.
An example like in your case would be if all the vehicles have a number, it is a common property, then there isn't a point in writing the same getNumber() method for each class that derives from that class. The abstract vehicles class is like a 'framework' of sorts, and the concrete classes (car, bus, van) that derive from the vehicle class is the actual class that you instantiate. In this class you can have more specialized variables and methods, (is the car a 2 wheel or 4 wheel? A truck probably doesn't need that method)
Related readings from this SO question: Purpose of Abstract Classes
In short the beauty of abstract classes is that you don't have to be concrete (lol) about every single detail, yet you can have one method for across all common classes, and override them if they are special cases. This helps in maintaining code too (A bug in a common method shared across all classes only requires change in the abstract class and not all of the concrete classes)
Additional Info
Just as additional info, if you did use an interface and NOT an abstract class, then you would HAVE to override each method there, as an interface does not contain the implementation, only the design. This link helped explain things to me last time.
You might also want to read up on Polymorphism and Inheritance, important concepts in all Object oriented Programming (OOP) languages. :)
Note: Also, since I can't comment on your question (not enough rep) yet but have been lurking on SO long enough, don't be discouraged by the downvotes, many here assume you have the right keywords too search for on StackOverflow to get the answer you want but this isn't always the case. Good luck!
You can leave it in the superclass and not implement it in the subclass.
calling
car BMW = new car();
BMW.getNumber();
should grab the superclass method.

Purpose of having super class as an abstract class in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Super class being an abstract class creates an overhead for all its sub classes to compulsorily define its abstract methods. I understand that it's very basic but I need to know why do programmers usually make super class as an abstract class, though we can do similar things using a super class as a non abstract class.
An abstract superclass is one way to provide re-usable code.
You can extend the abstract class and inherit the code. This is sometimes more convenient than using static methods or object composition to share code.
The abstract class can "fix" parts of the code (by making it final). This is called the "template method" pattern (and this is not possible with an interface, which cannot provide final methods).
Of course, you can achieve both with a non-abstract superclass as well.
An abstract class has the additional benefit that it does not have to provide a complete implementation (that would make sense to instantiate on its own), some parts can be left specified, but unimplemented (the abstract methods).
imagine you have a common behaviour where only small details are specific to the implementation - then you can put all the common behaviour in a abstract base class and having some abstract methods that the implementing classes need to fill.
For example a abstract repository base class might implement all the details to contact your server, etc. and concrete repositories just need to fill in the details to read the right object from the right table, etc.
Abstarct classes are meant for 'abstracting'. means if some classes are having common behaviour, instead of writing evry time the same thing in each class, write that in one class and ask the other classes to use it [by making the classes as subclasses to the abstract class]. This is nothing but inheritance. To summarise: Use abstract classes when you want default behaviour for some classes Use interfaces when you want different behaviour different classes.
For More explanations Refer below links:
http://www.javacoffeebreak.com/faq/faq0084.html
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
several usage of abstract class:
act as the protocol when tranfering data between objects, the two customers need not to know other class's structure. ----- just like the interface
define the abstract operation, which hides the detailed implementation of concrete class, for example, I have a class called AbstractPayment, which define the opration of charging money from customer, then the concrete classese of it could be: PaypalPayment, AlipayPayment, BankPayment and others. BUT, for the class customer, it only needs to know the AbstractPayment.
after some time, if you need to add another ConcretePayment, or modify one other payment, the customer class won't change.
Abstraction is largely used in design patterns, I suggest you to read following:
Abstract Factory Pattern
STO

practical situation to use an abstract interface? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was trying to understand when it can be useful to create an abstract interface.
I know that if you create an interface the methods have to be public, so is nice for a service. But what happens if service is an abstract interface? Does that make sense?
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
I this is a correcte implementation?
Finally after a lot of people that can sleep by my fault I write my solution, ty for waiting.
package cat.base.gpt.domini;
public interface IExpMS extends Serializable{
... methods here..
}
public interface IExpMSDetallGIM extends IExpMS {
more methods here..
}
public interface IExpMSDetallOGC extends IExpMS{
..no methods just inheritance.
}
package cat.base.gpt.domini.impl;
import cat.base.gpt.domini.IClauExpedient;
import cat.base.gpt.domini.IExpMS;
public class ExpMS implements IExpMS{
..atributs and #overide methos interface
}
public class ExpMSDetallGim extends ExpMS implements IExpMSDetallGIM {..}
public class ExpMSDetallOGC extends ExpMS implements IExpMSDetallOGC {..}
*every method is public, atributs are private. maybe i can write methods in the interfaces protected, but i'm not really sure...if someone needs to see full code i can't post or send by email.
if ypu wanna see the databasze views to think about my solution here there are:
![IExpMSDetallGIM4
ty.
Interfaces are always abstract. They define the interface of a class, so they are only about public methods, regardless the language, I think.
And while private methods are implementation detail and NOT the interface, they cannot be declared in an interface.
If you want a private method to be the same in a set of classes, you can create a base abstract class with protected methods.
Abstract means "you cannot create a member of this type".
Interface is just a description of some of the classes' properties. They are always abstract, while you cannot create an instance of an interface.
Look at the link http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/ - it describes the code in C#, but it's the same thing, only the keywords differ.
i'm working with java..is the same?so interface = abstract interface?
In Java 7, yes. In Java 7 (or earlier) an interface is implicitly abstract. The interface itself does not include bodies for any of the methods that it specifies, so it makes no sense to create an instance.
In Java 8, it is possible to include default methods in an interface. These default methods have bodies with executable code in them, but (naturally) they cannot refer directly to the state of an instance. (Instance state variables are declared in the classes that implement interface ... and the default methods can't refer to stuff that has not, and may not ever be declared.)
However, you still cannot create an instance of a Java 8 interface, so it is still abstract in the sense that an abstract class is abstract.
You then ask this:
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
That is correct ... but it is nothing to do with what the abstract keyword means in Java. In fact, that is describing how all Java classes behave ... vis-a-vis the visibility of private members.
The primary purpose of interfaces is to allow multiple different implementations of "the same thing". The user of the interface is not dependent on the particular implementation and this allows for good separation of concerns. New implementations can be added later and the program can be extended, without ever need to modify the code that is using them.
Imagine how you would write a program for summing up numbers from various data sources. You could write one separate program for every type of data source (e.g. csv, xls, database table). But then, the "summing up" logic would be repeated. If you wanted to add a new data source type, you'd have to write a whole program from scratch.
Interfaces allow to make it more flexible. You realize, that your summing up logic needs to operate on a list of numbers. It doesn't care where those numbers come from. So you define an interface:
interface NumberListProvider {
List<Double> readNumbers();
}
Then you make your whole complex algorithm dependent only on this interface and you provide different implementations (concrete classes), reading the numbers from csv, xls or various databases.

Categories

Resources