java - My understanding of when to use Abstract class or Interface -


i wish validate understanding of when/why use abstract or interface.

my example related humans. human can man or woman. human can have different profession in life. how use them:

i declare professions interface, because establish contract of human can in profession. example:

interface softwareengineer{  code(); }  interface truckdriver{  drivetruck(); }  interface pilot{  flyplane();  } 

and declare man , woman abstract class- because man , woman person is.

abstract man{  }  abstract woman{  } 

the class use define person can implement profession interface define person can , person extend abstract class define he/she is.

class mark extends man, implements softwareengineer{    code(){    } } 

this how explain 1 interface , abstract difference understanding. wondering how answer below 2 questions:

  1. you can not instantiate abstract class , if make man , woman abstract how can instantiate these class. how can of use then?

  2. why did make man , woman abstract, why can't make them interface. class implement them instead of extending.

these questions ask myself. might missing here. appreciate insights in example.

an interface contract outside world, best face forward. in way, allows implement multiple inheritance in java.

an abstract class there provide common set of functionalities can shared subclasses, e.g., attributes, fields, etc.

now, let's go on examples have provided in posting.

  1. man , woman didn't need abstract classes if instance of man or woman can exist without profession. thus, can concrete classes.
  2. you don't want man or woman interface. avoid class implement both man , woman interfaces.
  3. by being abstract classes, man , woman classes can provide common set of functionalities.
  4. a class named mark not suitable name concrete class extends man , implements softwareengineer. may mansoftwareengineer better name (i know it's subjective). however, mark name instance of mansoftwareengineer

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -