-3

I'm studying for an exam about multi-threading, I started an exercise by myself in order to improve my ability with Java but I have a question:

Am I able to extend a class with another class made by me that extends Thread too?

I'm aware I can extend only 1 class in Java (and that I could implement Runnable, though I'm not very comfortable with that right now), but can I do it in cascade as said before? Or am I forced to use implements? I'll throw my example to make you get exactly what would I do:

Character class -> extends Thread
Warrior class -> extends Character
Wizard class -> extends Character

and If I can do it, where could I use the super() function?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Geologo
  • 5
  • 2
  • 5
    To summarize, you question seems to be: How does subclassing work? How do interfaces work, and how does threading work? This is too broad. – ControlAltDel Sep 08 '16 at 13:53
  • I'm not sure how you got to the multi-threading part of class without going through the inheritance part first. – RealSkeptic Sep 08 '16 at 13:54
  • You can extend a class, yes. You can also _try_ before asking. – Marko Topolnik Sep 08 '16 at 13:54
  • 5
    Without seeing any actual code, I have to say that for classes with names such as "Character", "Warrior", and "Wizard" to be subclasses of `Thread` has pretty bad code smell. – John Bollinger Sep 08 '16 at 13:57
  • Did you mean `Wizard class -> extends Warrior` ? – c0der Sep 08 '16 at 14:56
  • I know my lacks about Object Oriented Programming, but I'm trying to get mostly the part of cuncurrent tasks of this exam, because it is focused on it. I obviously tried before to ask, and I asked because it didn't work, but I think it was not a problem with the super() call at this point :/ – Geologo Sep 09 '16 at 17:29

2 Answers2

0

There's no problem doing that as long as your Character class is not declared final. Each subclass of Character inherits (indirectly) all the (non-private) behavior and structure of Thread (and also of Object) as well as the behavior and structure of Character. They can all be used as Thread objects.

The call super() invokes the default (no-argument) superclass constructor. It can only be used as the first line in a sub-class constructor. You can use the super.blah() syntax anywhere in your subclass code to invoke the superclass's blah() function.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

As you mentions, a class can only inherit (extend) from one other class But hierarchical structure of extending classes does exist.

For example, you could have a

public class Animal{
}

public class Mammal extends Animal{
}

public class Monkey extends Mammal{
}

the super() is used within the constructor of each class

Kesem David
  • 2,135
  • 3
  • 27
  • 46