#why use abstract class, when there is an interface?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
There are several reasons why you might choose to use an abstract class instead of an interface in Java:
-
Code Reusability: Abstract classes can provide a default implementation for common methods, allowing subclasses to inherit and reuse that code. Interfaces, on the other hand, cannot contain any implementation details.
-
Flexibility: Abstract classes can have both abstract and non-abstract methods, whereas interfaces can only have abstract methods. This allows you to define a mix of common functionality and enforce certain behaviors through abstract methods.
-
Evolution: If you add a new method to an interface, all classes implementing that interface will need to provide an implementation for the new method. However, with an abstract class, you can add new methods without affecting existing subclasses as they are not required to implement all the methods.
-
Multiple Inheritance: Java does not support multiple inheritance of classes but allows implementing multiple interfaces. So if you need to inherit from multiple base classes or have multiple types of behavior, using interfaces may be more appropriate.
-
Access Modifiers: Abstract classes can have different access modifiers (public, protected, etc.) for their members, whereas interface members are always public by default.
In summary, while interfaces are useful for defining contracts and achieving loose coupling between components, abstract classes provide more flexibility and code reusability by allowing default implementations and mixed behavior. The choice between using an abstract class or an interface depends on the specific requirements and design considerations of your application.
bots answer is quite accurate
Closed the thread.
I'd like to add some information, since java 8 interfaces can also hold default methods contain implementation details as well(bot mentions it can't in point 1 and 3) .
you cant override default methods though iirc
Wym? It will mostly follow default implementation incase of clash (multiple interfaces) you can override that behavior. Idk if you can override it regardless, but that's the whole point behind this so you don't break all the classes but still have a functionality piped down.
@latent oxide
if u want to have a good read, here is an explanation of both with usecase differentiation:
@latent oxide
An abstract class denotes a yet unfinished class. For example, it might be only done to 70% but there are still 30% missing. As such, it is used to create a template for other classes that extend it. The extending class can then concentrate on only doing the remaining 30% since 70% are already done. This can greatly reduce code duplication.
In general, a class is abstract if it has an abstract method. An abstract method is a method that is missing any implementation:
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
String getName() { // regular method
return name;
}
abstract void makeNoise(); // No method body
}
Since the class is not finished yet and makeNoise is lacking any implementation, it is impossible to create instances of it in that state:
Animal animal = new Animal("Buddy"); // Does not compile! Can not instantiate abstract class
However, we can use it as template for extending it and get the existing name-functionality for free (getName()). But then we are required to implement everything that is still abstract, i.e. incomplete like makeNoise:
class Dog extends Animal {
Dog() {
super("Buddy"); // all dogs are called Buddy
}
@Override
void makeNoise() {
System.out.println("Wuff Wuff");
}
}
And now we can create instances of it and use the methods:
Dog dog = new Dog();
System.out.println(dog.getName()); // Prints Buddy
dog.makeNoise(); // Prints Wuff Wuff
@latent oxide
An interface defines a set of method signatures, as contract. It can greatly increase code modularity. Often, interfaces are property-driven.
interface CanWalk {
void walkLeft();
void walkRight();
}
There is no method body. So if a class implements CanWalk, he makes the promise to offer those methods:
class Player implements CanWalk {
int x;
@Override
void walkLeft() {
x--;
}
@Override
void walkRight() {
x++;
}
}
Someone could now demand a CanWalk instance and use the methods:
class Mover {
static void moveAround(CanWalk canWalk) {
for (int i = 0; i < 10; i++) {
canWalk.walkRight();
}
canWalk.walkLeft();
canWalk.walkRight();
}
}
Note that the moveAround accepts everything that can walk.
Mover.moveAround(player);
We could also give it a Dog, as long as it implements CanWalk.
You have two options to create instances of interfaces:
- Create a class that
implementsthe interface, likePlayer - Use an anonymous class:
CanWalk canWalk = new CanWalk() {
@Override
void walkLeft() {
System.out.println("Walking left");
}
@Override
void walkRight() {
System.out.println("Walking right");
}
};
An interface that only offers one method is called a functional interface:
@FunctionalInterface
interface IntOperation {
int operate(int a, int b);
}
You have two additional options to create instances of it:
3. Lambda expression
IntOperation operation = (a, b) -> a * b;
System.out.println(operation.operate(5, 3)); // Prints 15
- Method reference
// Method in MathUtil
static int multiply(int a, int b) {
return a * b;
}
// Use it as
IntOperation operation = MathUtil::multiply;
System.out.println(operation.operate(5, 3)); // Prints 15
there is method body, if i use default before method
Thank you, Zabuzard !
A thread-safe class in Java is a class that can be safely used by multiple threads concurrently without causing any data inconsistency or unexpected behavior. It ensures that the class's methods and operations are properly synchronized to prevent race conditions and maintain data integrity.
Thread safety can be achieved through various techniques, such as using synchronized blocks or methods, using atomic variables, or using thread-safe data structures provided by the Java concurrency library. By making a class thread-safe, developers can ensure that it behaves correctly and consistently in a multi-threaded environment.
In Java, the "synchronized" keyword is used to create synchronized blocks or methods.
When a block or method is marked as synchronized, it means that only one thread can access that block or method at a time. This ensures that multiple threads do not interfere with each other while accessing shared resources.
Synchronization is typically used in multi-threaded applications where multiple threads are accessing and modifying shared data. By using synchronized blocks or methods, developers can prevent race conditions and ensure thread safety.
When a thread enters a synchronized block or method, it acquires the lock associated with the object on which the block or method is defined. Other threads attempting to enter the same synchronized block or method will be blocked until the lock is released by the first thread.
Synchronization can be applied to blocks using the following syntax:
synchronized (object) {
// code to be executed by a single thread at a time
}
Synchronization can also be applied to methods by adding the "synchronized" keyword before the return type of the method:
public synchronized void methodName() {
// code to be executed by a single thread at a time
}
correct. but ur still going against the intention if u abuse that
which leads to confused users
if u want to create a class template, u should use an abstract class
and not abuse interface default methods
especially bc they are so limited
for example, no properties/fields
interfaces have no state
the default methods have been added to allow for library devs to add new methods to an already existing interface without breaking backwards compatibility
and generally, thats the best way to use them
and not as some sort of mini-abstract class
a really good example of a well done combo is
List, AbstractList and ArrayList in the JDK
- interface contract
- helper class as template for implementations
- concrete implementation using the helper
Btw is there a better naming for the second? I recently used that structure and AbstractXXX sounds meh, but I can’t think of smth better
but that can confuse in some contexts
ok, got it
thank you, Zabuzard!
@empty shale also. Can you suggest book/course/guide to learn Threads? All if find is - Threads Introduction or some other basic stuff, where they only describe implementing Runnable or extending Thread classes. I want to know bare minimum for junior developer + what thread-safe classes are and how to write them
https://www.baeldung.com/java-concurrency
this might help you while working through a book/course but doesnt work as a course on its own
This is essentially the difference between interfaces and abstract classes. IMO you should always choose interface and then when you get to a point where you can't avoid adding state, an abstract class (that implements the interface) is introduced.
thank you, Connor

wanna put some more emphasis on this. default methods are Java's approach to handling what extension functions handle in other languages, a way to add functionality to an existing type
definitely shouldn't be used as an alternative to abstract classes
@latent oxide
Your question has been closed due to inactivity.
If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.
Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.
When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.
Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.
With enough info, someone knows the answer for sure 👍
The start method is used to start the execution of a new thread. When you call the start method on a Thread object, it creates a new thread and invokes the run method of the Runnable object associated with that thread.
The reason for this separation is that the run method contains the code that will be executed in the new thread. However, if you were to simply call the run method directly, it would execute in the same thread as the caller, without creating a new thread.
By calling the start method, you are instructing the JVM to create a new thread and invoke the run method in that separate thread. This allows for concurrent execution of multiple threads, which can be useful for tasks that can be performed independently and concurrently.
do not extend Thread
ok, why?
To create a method that is restricted by the number of requests to an API in Java, you can use a combination of variables and conditional statements. Here's an example:
public class APIClient {
private int requestCount = 0;
private final int MAX_REQUESTS = 5;
public void makeAPIRequest() {
if (requestCount < MAX_REQUESTS) {
// Perform API request here
System.out.println("API request made");
requestCount++;
} else {
System.out.println("Maximum number of requests reached");
}
}
}
In this example, we have a class APIClient that has an instance variable requestCount to keep track of the number of requests made. The maximum number of requests allowed is defined as MAX_REQUESTS.
The makeAPIRequest() method checks if the current requestCount is less than the MAX_REQUESTS. If it is, it performs the API request and increments the requestCount. Otherwise, it prints a message indicating that the maximum number of requests has been reached.
You can then create an instance of this class and call the makeAPIRequest() method to make API calls while ensuring that you don't exceed the maximum allowed requests:
public class Main {
public static void main(String[] args) {
APIClient apiClient = new APIClient();
for (int i = 0; i < 7; i++) {
apiClient.makeAPIRequest();
}
}
}
In this example, we are making 7 API requests in a loop. However, since the maximum allowed requests are set to 5, only the first 5 calls will be successful, and subsequent calls will print a message indicating that the maximum number of requests has been reached.
To create an object and make a POST request with it in the body using HttpRequest in Java, you can follow these steps:
- Create a class representing the object you want to send in the request body. For example, let's say we have a
Userclass withnameandemailfields:
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and setters
}
- Create an instance of the
Userclass with the desired values:
User user = new User("John Doe", "[email protected]");
- Convert the
Userobject to JSON format using a JSON library like Gson:
Gson gson = new Gson();
String jsonBody = gson.toJson(user);
- Create an instance of
HttpRequestand set the request method to POST:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://example.com/api/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
- Send the request and retrieve the response:
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print the response body
System.out.println(response.body());
Make sure to handle any exceptions that may occur during this process.
Note: This code requires Java 11 or later as it uses the new HTTP client introduced in Java 11. If you are using an older version of Java, you can use libraries like Apache HttpClient or OkHttp for making HTTP requests.
@latent oxide you know, you can ask us instead of chargpt
Letting people extend thread was a mistake, you should only pass a runnable to its parameter
of course i know. I think i am the leader in amount of help posts on this server. I ask GPT questions only to make sure, that info, that i read, is correct or to find shorter solutions, when i am sure in topic
The object you provided is called a JSON object. JSON stands for JavaScript Object Notation, and it is a lightweight data interchange format commonly used for transmitting data between a server and a web application.
In the JSON object you provided, "importRequest" is a key, and its corresponding value is set to true. This means that the value of the "importRequest" key is a boolean value (either true or false).
The number 109 in your example does not have any specific significance without further context. It could represent any numerical value or be used as an identifier within the JSON object or the system utilizing it.
i am given this object: ```
JSON документ: {"description":
{ "participantInn": "string" }, "doc_id": "string", "doc_status": "string",
"doc_type": "LP_INTRODUCE_GOODS", 109 "importRequest": true,
"owner_inn": "string", "participant_inn": "string", "producer_inn":
"string", "production_date": "2020-01-23", "production_type": "string",
"products": [ { "certificate_document": "string",
"certificate_document_date": "2020-01-23",
"certificate_document_number": "string", "owner_inn": "string",
"producer_inn": "string", "production_date": "2020-01-23",
"tnved_code": "string", "uit_code": "string", "uitu_code": "string" } ],
"reg_date": "2020-01-23", "reg_number": "string"}
Detected code, here are some useful tools:
@ebon garden how is that possible: 109 "importRequest": true?
Wdym
there is always pair in map (key: value)
so how is there a number 109?
caught in 4k
can you have a look?
.
is it a mistake in documentation or a real thing?
hm you mean like the 109 makes the json invaldi right?
yes
Hi, Connor btw!

where you got that json from?
From job interview
i guess so
I doubt that was on purpose
Firas, what do you think?
