Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello I'm a freshman in college. And just did a research about object oriented programming and the language that i'm studying is Kotlin, But i couldn't find a real reason why we need to use abstract class or methods at all.
For example :
abstract class Student(name: String, age: Int) {
init {
println("Student name is: $name")
println("Student age is: $age")
}
//non-abstract function
fun demo() {
println("Non-abstract function of abstract class")
}
//abstract function
abstract fun func(message: String)
}
class College(name: String, age: Int): Student(name, age) {
override fun func(message: String) {
println(message)
}
}
fun main(args: Array<String>) {
val obj = College("Chaitanya", 31)
obj.func("I'm a Blogger")
obj.demo()
}
reference : https://beginnersbook.com/2019/03/kotlin-abstract-class/
How is this showing only the essential data?
The purpose of abstraction is so you can ignore details that aren't relevant to you. When I'm working with a list of objects, I normally want to add, remove, and iterate. I don't want to worry about resizing an underlying array or adding and removing linked nodes. By using the abstract interface List, I can put those details inside a box and not have to think about them.
Abstract classes are only one kind of abstraction and are usually less important than interfaces. Their main usefulness is to allow you to collect common characteristics in one shared place to reduce duplication. For example, if I have a List, I always need a way to iterate over it, and there's no more efficient way to implement the contains method than to iterate over the list to look for the item. I can put this method in an abstract class, and then the actual implementations of the list (array, linked, something else) only have to provide a way to iterate.
Simply
Actually purpose of abstraction is selecting data from a larger pool to show only the relevant details to the object. It helps to reduce programming complexity and effort
Abstract class is that it allows you to group several related classes as siblings and it helps to reduce the complexity of the design and implementation process of software.
And abstract classes help to describe generic types of behaviors and object-oriented programming class hierarchy. Also it describes sub classes to offer implementation details of the abstract class.
Abstract methods are mostly declared where two or more sub classes are also doing the same thing in different ways through different implementations.Also it extends the same Abstract class and offers different implementations of the abstract methods.
Related
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
J. Bloch in his Effective Java written for Java 6 mentioned the following (Item 17):
If you feel that you must allow inheritance from such a class, one
reasonable approach is to ensure that the class never invokes any of
its overridable methods and to document this fact. In other words,
eliminate the class’s self-use of overridable methods entirely.
Item 18:
If you use abstract classes to define types, you leave the programmer
who wants to add functionality with no alternative but to use
inheritance. The resulting classes are less powerful and more fragile
than wrapper classes.
While interfaces are not permitted to contain method implementations,
using interfaces to define types does not prevent you from providing
implementation assistance to programmers.
Now in Java 8 with its default method's implementation (using the other methods in the interface) interfaces are dangerous for inheritance.
For instance:
public inteface MyInterface{
public void compute(Object o);
public default void computeAll(List<Object> oo){
for(Object o: oo)
compute(o); //self-use
}
}
So, according to J. Bloch, it may introduce some problems when we try to implement the interface, because:
Overriding the methods like this (similar to what J.Bloch provided):
public class MyInterfaceCounter implements MyInterface{
private int count = 0;
#Override
public void compute(Object o) {
count++;
}
#Override
public void computeAll(List<Object> oo){
count += oo.size(); //Damn!!
MyInterface.super.computeAll(oo);
}
}
The client access the interfaces's internals, i.e. they have to know about the default implementation.
What to do with it in Java 8? Are the rules from Effective Java apply still applicable?
Moreover, we can't declare the default method as final (as we can do for classes, it would make the self-use not too dangerous for overriders).
Okay, take the answer from your previous question and look what we can apply here:
You could simply avoid self-use.
In this case you can't. While implementing that interface your only choice to rely on (if you want to give a default implementation) is the method compute. You have to use it or not give an implementation at all.
You could make one of the methods involved final, so it can't be overridden.
That won't work in an interface as well.
You could make the class final, so it can't be extended.
That won't work in an interface.
You could describe the class's self-use patterns in its Javadoc comment (meeting the requirement of letting other people know).
That is the only choice left here. Either document it or don't give a default implementation.
So yes, the basic idea of it still applies, however your choices are somewhat limited.
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
I'm looking for a definition of an abstract object. I cannot find it in my textbook and I've tried googling. Abstract classes and methods I understand. Anyone know what an abstract object is?
There is no such thing as an abstract object, because an object would imply something is real, and an abstraction cannot be real. Because it is abstract.
In layman's terms, you cannot instantiate abstract classes, and an instantiated class is an object.
There are abstract classes and methods, there is no such thing as an Abstract object.
You cannot instantiate an Object from an Abstract class.
You have to make another class extend it and override all the abstract methods it has.
This is why abstract classes are used, to put some constraints on a set of classes that have to extend it.
You should look into inheritance to see why abstract methods are used.
The fact that the notion of Abstract Object is not modeled in the language doesn't necessarily mean that it makes little sense. When we use objects and messages to represent elements of a given reality or fantasy some of them will have a more concrete meaning than others. For instance, if classes are first class objects in your system (cf. Smalltalk,) these objects could be deemed abstract when compared to their instances because they do not represent the thing but the concept associated to such a thing.
For example, the class WaterMolecule would be concrete as a class, its instances -representing H2O molecules- would also be concrete (as stated in the previous answers to this question) but the class WaterMolecule itself, when considered as an object, would fit the notion of an abstract object.
We could say that a class is an abstraction of level 1. An example of abstract object of level 2 would be the class of the class, namely the metaclass. If the metaclass is represented in the language as an object, this would qualify as an abstract object of level 2. Note that you can go a step further and consider the class of these objects, which would qualify as a concrete class (its instances are metaclasses) and, at the same time, as an abstract object (of level 3.)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
First day using Java. Very basic question: I have three base classes, multiply-inherited by many classes. Each of these base classes has lots of implementation with few abstract methods:
class Consumer { /* lots of stuff */ };
class Producer { /* lots of stuff */ };
class Logger { /* lots of stuff */ };
class A : public Consumer, Producer, Logger {}
...
class Z : public Consumer, Producer, Logger {}
Now I know I can turn two of three base classes into interfaces and multiple-inherit the 2 interfaces and extend one class. Inadequate because of all the implementation in these base classes that doesn't make sense to duplicate into many subclasses.
I'm reading some stuff on delegation or composition, and I don't know how to apply this here. Basically my thought processes have been patterned by my C++ experience. What is the path of least resistance to convert my C++ class structure to Java?
I can fill out the base classes more if needed, but hopefully not necessary.
What is the path of least resistance to convert my C++ class structure to Java?
take a pen and paper, rethink your problem and make a design that's closer to how Java works.
There's no magical rule that will transform any given problem with multiple inheritance into another without it. Given the situation, you may want to separate concerns by creating multiple classes with a reference to each other, whereas you had only one in C++… But then it's up to the specific problem you're dealing with, how you'd build your hierarchy of classes and interfaces and how the resulting different class instances will relate to each other.
you have two options:
Create 3 interfaces for Consumer, Producer and Logger and make the classes A and Z implementing them. Of course for each class you have to provide an implementation. If the implementation is the same make a more generic class (it could be abstract, you probably won't need to instantiate it) implementing the 3 interfaces and then make the classes A and Z extending the abstract class.
As you said in your post it seems this solutions don't fit your needs , so use delegation instead, in the classes A and Z put 3 new fields (as instance variable) of Consumer, Producer and Logger type (you can instantiate them in the constructor) and then put methods which are wrappers for the Consumer, producer and Logger methods.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
From an old exam with no solutions:
Given this code....
import java.util.*;
public class AClass {
private int f(List<Integer> list){
int i = 0;
//Something useful
return i;
}
public int g() {
List<Integer> myList = new LinkedList<Integer>();
return f(myList);
}
}
Note that the method f is polymorphic, i.e. it can be passed any implementation of the interface List. On the other hand, the method g is not. As it constructs the object myList, it cannot do this without knowing its type. Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What is the name of the standard solution to this problem?
Describe it in this case
Loose coupling There are many ways to solve that problem among them: program to interfaces and apply Dependency Injection
Method g() is tightly coupled to LinkedList because the method is explicitly instantiating that object hence tight to that class. If you want to for example use an ArrayList you need to open the class and explicitly modify the method and potentially introduce bugs. Additionally, you will probably need to retest and document. On the other hand method f() is way more flexible because you can just pass the collection you need and the method has no notion about the concrete implementation you are passing keeping in that way your method closed.
Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What do you mean by that? Please provide an examples. The only way to make this code more generic is to use Collection or Iterable instead of List, but I'd say that's an overkill in terms of loose coupling.
Apparently, the solution in this case would be to create an Abstract Factory Pattern.
For example, we'd create a new class called AClassCreator and have a method createAClass(List<?> list) where the parameter is a subclass of list.
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 9 years ago.
Improve this question
I am working on a java class for parsing HTML and generating RDF (which I think I will eventually split into two classes - one for parsing and one for generating RDF).
At the moment I am creating a lot of methods for checking HTML data and converting it into a more uniform representation. Some of the methods I have created so far are:
public boolean isInteger(String str) { }
public boolean isTime(String str) { }
public boolean isDate(String str) { }
public String dateConverter(String[] date) { } //Converts a Norwegian date into mmddYYYY
Should I put methods like these into a util class? At the moment they are only being used by this specific class, but I think that they might need to be use them by more than this one class at a later point in time.
Well, yes, the methods you listed look like good candidates for public static methods in a util class. (The last 2 or 3 would fit nicely in a class called "DateUtils", for example.)
Of course, if you only use them in one place, they can just as well remain "private helpers" there, but as soon as you have multiple places using them, a util class makes sense.
(Edit: overuse of static methods can be problematic, but I think these methods could well be static utils because they are pure functions.)
They seem generic enough to be appropriate to put in a util class. I would, at the very least. Basically any class that parses String in your code would need to use those methods. I would make them static before adding them to the class though to avoid unnecessary construction.
Decomposition is a good habit to get into. If you are unsure about whether or not you need to use them, then go ahead and do so. It will give you practice with using utility classes.
It is a good practice to collect such methods in a utility class. Even if they are called from a single class at the moment, these kind of methods will be potentially reused by other clients in a near feature.
However, you must pay attention to make this utility class easy to be reused. To do this, the method signatures, actually their arguments, must be as generic as possible. They should not take inputs specific to a class.
Another advice of mine is dividing this utility class into more than one classes, if it begins to contain many incoherent methods. You can do this by grouping the relevant methods in a separate class. For example, methods you wrote can be moved to TypeUtils class and you can collect conversion related methods in Html2RdfUtils class for instance.
Finally, if you feel that these utility classes can be benefical to your other projects, you can collect them in a distinct library.
if you eventually want to split them into two classes, you may want to define the baseclass as interface or abstract class.
Base on your requirement, abstract class should be the right choose.
Put something in common from the child class to the abstract class.(You can implement method in the abstract class)
from another answer, I want to ask a question?
the answer suggest putting static in front of the method to avoid unnecessary construction, it very make sense.
I know the abstract class does not require to be instantiated to call its method.
it also can avoid construction.
There is the question?
Which way is more legit? or better? or just same.