#Abstract class vs Interface

1 messages · Page 1 of 1 (latest)

gentle vector
#

Hello, sorry to disturb you all; I read a bit about abstract class and from what I've understood, an abstract class is one that contains "general" behaviors about an object and that object can't be instantiated directly.

Instead, its sub-classes are used to instantiate things.

Now, for interfaces, I'm confused, isn't it the same thing? What's the difference between and abstract class and an interface?

glad tideBOT
#

<@&987246399047479336> please have a look, thanks.

patent eagle
#

on the technical side they are fairly similar, yes

#

however, in practice they are used for completely different things

#

and often they also go hand in hand

#

if u read the following two posts ull understand:

glad tideBOT
#

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
#

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:

  1. Create a class that implements the interface, like Player
  2. 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
  1. 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
patent eagle
#

template vs contract

next shale
#

operationally, abstract classes can contain fields while interfaces cannot

#

everything else follows from that

gentle vector
# patent eagle template vs contract

hmm from what I've understood, an interface gives the the abstract method that we should implement in whatever subclass that inherits form the interface.

On the other hand, an abstract class is defining 70% of things that will already be same, like hardcoded things certain methods while 30% is the abstract method where we would need to apply our own logic in the sub-class inheriting it.

So template vs contract, in the sense that template, 70% is already there, built up the 30% on your own, contract in the sense that, we have defined the abstract methods that need to be implemented, it's mandatory, implement them and add the logic you want ?

fierce dirge
#

@gentle vector I really recommend going through MOOC. I don't mean to be rude, but you keep asking random questions about fundamental topics covered in it.

patent eagle
gentle vector
fierce dirge
#

You need to learn the language in a structured manner.

#

Or buy Head First Java.

patent eagle
#

most importantly u need to get ur hands dirty. a lot of stuff automatically makes sense once u work with it instead of only reading

fierce dirge
#

Please also apply what you learn.

gentle vector
#

yep, you guys are right, will try to put theory into practice instead of just reading and study in a more structured way

fallen raft
#

interfaces do not contain state

#

interfaces are also abstract. the actual definition of an interface is java public abstract interface MyInterface { public abstract void myMethod(); }

#

abstract classes & interfaces are forms of abstraction. interfaces focus on abstracting behavior

#

abstract classes do the same, but they typically contain state & at least 1 method that isnt abstract

gentle vector
patent eagle
#

neither. but if it doesnt even have state (fields), what purpose does it server then? none

#

remember the motivation for an abstract class. a template to ease development of a class or interface implementation

#

if it doesnt provide anything then there is no reason for it to exist

gentle vector
#

Yep I see, thanks !

gentle vector
patent eagle
#

interfaces and abstract classes are used for totally different things and often also together. even if they are similar on a technical level

gentle vector
#

yep I see, will have a better understanding when I will work with them, ty !

glass estuary
#

In a design phase when you are just fleshing things out, you don't want to 'use up' your only ability to extend a class prematurely. That's why you should reach for interfaces by default, then classes. I only consider abstract class as a point of refactoring when I have too many classes that implement the same interface and there is some COMMON STATE between them. Otherwise, I almost never want to see abstract classes around.

fierce dirge
#

I recommend just taking Zabuzard's input into account and skipping Surly's.
@glass estuary Please make sure to add the proper nuance, and not just reword other (generated replies).

patent eagle
#

isn't that essentially what the bot answer says as well, just in different words?

like, u make interfaces, u make classes implementing them and then u realize that some of ur classes have duplication. so u make a common parent class that acts as template where u move that duplication to. and that's what leads to abstract classes

#

(or u anticipate such a duplication in advance already. or ur a library developer and want to give ur users an easy way to implement ur interfaces)

glad tideBOT
#

@gentle vector

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 👍