The second method is called delegation. There is also composition - when A
is a member of B
.
The difference between the two is that if A
is not in the same package as B
(package access is a different case - left as exercise for the reader) - then in case of delegation or composition you will have access only to public data members and methods of class A
, whereas in case of inheritance, the inheriting class B
will have access to public and protected members and methods of class A
.
Update
There are a lot of additional differences even in the case that all methods and members of A
are accessible to B
(most of them relate to the case when you are not the owner of both classes, rather when A
is provided to you by a third party and you don't have control over its access modifiers).
But even if you do have the control and can define all of the members and methods of A
as public - do you want to? It would introduce a horde of additional maintenance issues - most important, IMO, is that anything you define as public is a contract between you and the user of your code - perhaps someone in a different part of the planet. Which in turn means that you can't hide your implementation details, your private utility methods or anything from him - nothing prevents him from using some method, that you wrote only for some inner calculation, directly.
What that means is - when tomorrow you decide that you don't want to maintain that method again or that it introduces some sort of performance or security issue - you can't remove it. Someone already uses it.
Another update
As mentioned below, and something that I haven't mentioned, in the case of inheritance you also receive a "free gift" - polymorphism. See here.