-3

I have two classes(not interface).

Suppose the classes be class A and class B.

I want to know which is more efficient and correct implementation.

I want to access the method of A from B.

Two ways: 1) class B extends A (inherits) 2) In class B: create an object/instance of Class A, and then access the method of class A.

Which one is more efficient and correct ??

SudeepShakya
  • 571
  • 3
  • 14
  • 34

2 Answers2

1

It depends. You should only use extends (for good OOP) if it is logically correct. The way I learned is with the "is a" test. If saying B "is a" A then extends would suit.

For example: Take 3 classes Dog, Canine and Fish

Dog "is a" Canine: this is logical and passes the "is a" test so we can use extends here
Dog "is a" Fish: this is not logical and should not inherit

If your class B is a logical subclass of A then go with extends.

Revive
  • 2,248
  • 1
  • 16
  • 23
1

You should read some documents about OOP (Object Oriented Programming). As you can read in the comments I would agree that it depends on your UseCase. A common rule for designing Objects is the 'Has a' and 'Is a' relations. This means if you can say MyObject 'Has a color' then You will add a color member to your Object as a property, if you can say MyObject 'Is a' bird then you will inherit - maybe - from Object MyAnimal that you have written before. There is a third way what you can do. If your method is a pure helper method - thus it does not own a sate while it is running, which means the method is defined within an object but does not use volatile members of that object for calculation - you could write a public static method and access it by MyObject.myStaticMethod(String myArgument). You have to be carefully with this kind of methods because if you don't know how to use them wright you can run into multiple problems e.g. when writing test or if you have a clustered environment.

But for now this should be fine. So make your objects granular over their properties and functionality. Methods that are not related to your object's type should be placed in Other objects that bundle this functionality - e.g. printString functionality in a printer Object- or if the methods are stateless then put them in a static statless helper object that bundles the functionality you need.

wstein
  • 29
  • 5