Why is a class called an abstraction of an object? - java

I understand that a class is essentially a blueprint of an object, but the idea that a class is an 'abstraction' of an object is a little hard for me to wrap my head around... If anyone could tell me the real meaning of the statement: "A class is an abstraction of an object", I'd be really grateful.
My confusion is because this statement has been interpreted differently by different people...
Does 'abstraction' mean:
Dealing with the basics of a system, and not the deep intricacies of that system?
or does it mean that:
Only an abstract class can be considered an abstraction of an object?
Thanks in advance,
Abhigyan

A class is a description of everything that will be in a certain type of object. For instance, a car will have a steering wheel, seats, dashboard, etc and functions such as accelerating, stopping etc. Each individual car is a car object, but the conceptual car is analogous to the class.
Dealing with the basics of a system, and not the deep intricacies of that system?
Somewhat, since a class does not usually describe exactly what goes into each field (for instance, the color of the steering wheel)
Only an abstract class can be considered an abstraction of an object?
No, this is more general that the abstract keyword in Java.
Basically, a class is an abstraction because it describes what is created, whereas an object is created itself.

A class can be instantiated into objects. It captures the characteristics that are common to all these objects.

A class defines fields & behavior (methods). It is instantiated into objects, which hold concrete values for those fields.
Abstraction as a term is used at many levels -- most commonly in regard of behavior. However in this regard it is being used of value.
We could state more clearly: A class is an abstraction across the possible values of its instances.
Example in pseudocode:
public class Cat {
String name;
String color;
}
object Cat ("Missy", "grey");
object Cat ("Whiskers", "orange");
object Cat ("Fluffy", "black");
As we see, class abstracts over values of its instances.

Related

Can Polymorphysim be achived using composition instead of inheritance ? (in Java)

I am learning Java, I know what inheritance and composition is, I saw numerous examples of polymorphysim showed using inheritance, so my first question is,can same be done using composition? If yes, please show with a small example.
My second question is, can it be said that polymorpysim is basically method overloading and/or is method overiding ? if yes, then why ?
First question
Polymorphism can be achieved in Java in two ways:
Through class inheritance: class A extends B
Through interface implementation: class A implements C.
In the later case, to properly implement A's behaviour, it can be done though composition, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
How can we create a new class implementing C with the same behaviour of X? Like this:
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
Second question
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
Method overloading consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
Method overriding consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be used as different classes/interfaces.
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be composed of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized implementations of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car interface that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at this. Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, this post has some good information, in particular tdammers's answer halfway down the page.
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
All Classes and methods are functions but not all functions are methods
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.

Usage of Generics in Java [duplicate]

Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.
Say I have:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
Should I use:
public class Person{
ICar car;
.
.
public Person (ICar c){
car = c;
}
}
or
public class Person<T extends ICar>{
T car;
.
.
public Person(T c){
car = c;
}
}
or does it depend on the tasks performed?
Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?
A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.
Think about what you try to mimic from the real world, before going into such programming details.
The distinction isn't always clearcut but here are a few clues:
Try to think of them as "type parameters" (Which they are.) They are associated with the class but they're not necessarily related to it. (Look at the collections framework for example.)
Type parameters can only be used if they don't change throughout an object's lifetime. This sounds quite obvious, but it's a very handy rule to decide when NOT to use generics. (Example is a person who can change cars.)
On the other hand, if not many instances will use the type parameter, if it's too optional, that's not a good idea either. (A lot of people might not have cars at all.)
And finally, a general thought that I found really useful: if you're unsure, don't be afraid to prototype it. Write the code both ways and check which one looks simpler and easier to comprehend. Show it to someone else without any explanations or maybe wait a day or two and then re-read the code yourself. Then throw the other one away. Throwing away code is good.
You need the generics version if you have any methods that take or return anything involving a T, or if it's possible for other people to access your car field. (Since you didn't show any methods, we can't really tell.)
For example, with the generics version you can have a method like T someMethod();, then when someone has a Person<Honda>, they know they can get a Honda back when they call someMethod, rather than some unknown type of car if you didn't have generics.
Similarly, with the generics version you can have a method like void anotherMethod(T anotherCar);, then when someone has a Person<Honda>, this forces them to pass a Honda to this method, instead of any car.
So basically, having a generic class allows you to place constraints on uses of the object later on (method calls etc.). If the constructor is the only place that you use T, and you don't need to use T in any methods or fields, then yes, there is no point for it.
This has to do with using Inheritance versus Composition.
Without knowing any other semantics, Composition seems more relevant. A person may change cars, without becoming a different person.
http://www.artima.com/objectsandjava/webuscript/CompoInherit1.html
http://en.wikipedia.org/wiki/Composition_over_inheritance
I'd tend to favor composition (what you're calling dynamic binding), especially in the case you use. A person is not a type of ICar, so using the generics here is kind of weird (to me anyway). I'd use generics as a way of saying "A container for ICar", as in Garage although in that case I might just use a collection type as a variable, or extend the collection type if really needed.
I'd suggest to focus on semantics first:
Providing that you may have a Bmw and a Toyota classes implementing the ICar interface, then make this question: can a Person change his car or would it be a different person if he does so?
The generics approach will force you to create a new Person instance if for some reason you need to change the value of the car attribute from Toyota to Bmw in an existent person instance and thus, this new person will be different from the previous one. Of course, you could create the first Person instance as Person<ICar> instead of hooking it to a specific car class but, why use generics then?

How to wrap my head around Object Oriented Design

Object oriented design is a pretty neat concept, but I'm struggling on how to wrap my head around most of its facets. I think the key to a good object oriented design is having a good grasp on how to look at it. I usually look at object-oriented this way:
Classes are Real-world entities or objects
Instance Fields are entity's attributes, ('has A')
Methods are like actions, verbs, Entity's abilities
Interfaces are like abilities that you can imbue on an object. It could also be an 'is A or can do' relationship whose implementations are not set in stone. Superman is a Krypton, being a Kryptonian comes with a set of special abilities, like flying, freeze-breath, etc. Superman fly different from Green Lantern and Goku and especially Batman, that is why Flight as interface is probably a good idea if you're creating a Fictional Universe.
public class SuperMan extends Man implements Kryptonian{}
public interface Kryptonian extends Flight, FreezeBreath{
public void fly();
public void coolBreath();
}
Problem comes along when you add Generics into the mix? Because the given type parameters somehow creates a contract between the class/interface and the type.
public interface Flight<T>{
public void fly(T t);
}
In this example, Flight is coupled with a T, T could be a superhero a bird or anything that can fly.But is that really how I should imagine it? Because that seems like the same as what plain interfaces do? Although, a parameterized interface is still an interface, the coupling with the type T is what really bothers me. Moreover, things also get complicated when you add bounded restriction on the parameter type.
public class Pidgey<T extends Bird> implements Flight<T>{}
what real-world concrete object can you identify T with? The above example is pretty wrong, although using the class parameter to also restrict the type of Flight is probably a good design, because Flight is still independent enough that other classes could still use it without any restriction. But the example itself is wrong. Pidgey is a Bird that can fly, but what what could T be? Well, T could be anything, it could be another object or abilities. The question is what are its implications, why put T there? What are real-world examples of doing so?
It's easy to understand when you talk about collections, since collections are like containers. You can create a wide variety of containers that holds different kinds of objects.
public class WaterBottle<T extends Liquid> implements UniqueCap{}
But I've seen Generics being used not just on a container-like objects? How could one design such objects, what did they consider?
Your analogies to the various features in OOP are definitely valid. Generics definitely make the most sense when talking about collections/containers/Hashmaps. They do have their uses in other places, though. For example, if a bank wants to process notes in many currencies, they can write
public class moneyProcessor
However, generics aren't required. In the context of your Flight interface, there wouldn't be much of a reason to use generics. Which brings me to another point:
Just because someone else does something one way doesn't mean you have to do it that way. OOP is very flexible for a reason. There's always more than one correct way. If a method takes an Object as a parameter, it's not the end of the world. Just make sure you can read it later. :)
Edit: and that others can read it too.
Its convention to use T when dealing with generics. it makes code readable as others reading your code will immediately know you're referring to a generic and nothing specific

Need to clear a minute concept about inheritance in general and its implementation in OOP. Please see

I am curious as to how the concept of "inheritance" takes place in the world of object oriented programming. Let me explain my dilemma (I came across this dilemma while studying Java but I hope that my question is generic in nature) :
Suppose there is a class A and a class B. Class A "inherits" Class B. What does this actually mean? Does the compiler make a "new" class, which is THEN instantiated into an object which contains the elements of both the classes A and B behind the scenes? If that's the case, then how are the access restrictions implemented according to the access specifiers?
For a moment, I wondered if it happens in the following manner :
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
But then, it occurred to me that there is a fault with this theory. Suppose two different classes, B and C are inheriting class A. Then, if we are going to make objects of class B and class C, then they'll have their OWN copies of the elements of class A. So this theory fails too.
I was just trying to explain the confusion about inheritance that I have in my mind. It's giving me headache. Please help.
EDIT : This is a link to a discussion related to my question which i found on this site.
Do subclasses inherit private fields?
I may fail, but I'm going to take a stab at an explanation on this for you.
In honesty, I think you may be making what is really a very classic mistake in how you conceive object programming - and that's making the distinction between objects and classes. Object creation in virtually any object-oriented language is one of construction based on a class definition. From your question, it sounds as though you are mentally modeling an OO language in general and object inheritance in particular as aggregating discrete objects, where in reality the objects are being defined in terms of aggregated class definitions.
public class A
{
public A();
}
public class B:A
{
public B();
}
public class C:B
{
public C();
}
In your A->B->C model, C's definition is in terms of its own unique properties plus all the members of its immediate ancestor, B, which, in turn, is defined in terms of its own unique properties plus all the members of its immediate ancestor, A. The process of creating the object is still a unique and discrete event, and the object, despite its multi-layered heritage, is still only one object at instantiation time.
Regarding the visibility of certain members: When a class author designs and builds a class, he makes certain decisions about what he makes available in two distinct perspectives: that which is exposed to consumers of the class, and that which is exposed or available to subclasses. Members and fields declared private are every bit a part of descendant classes, even if they are "contractually" forbidden to be accessed by subclasses. You could make a crude analogy that a TV has a "public" interface of an on/off button, volume control, and color controls, but has "internal" controls not intended for the consumer such as the internal electronic components, or the power supply. They're still very much there even though they are not "visible" or "available" to consumers or subclasses.
Now, that said, there are constructs in most OO languages that reflect the properties you describe - multiple objects - and that involve a design pattern known as Composition (or, sometimes, Aggregation. This is where a class isn't derived from an ancestor class - typically because the class is declared "sealed" (C#) or "final" (Java) (or other designation that prohibits inheritance). That forces a developer interested in using the class to make it a member of another class, such that when the an object of the class is instantiated, you DO have discrete objects of both classes.
You might have the following:
public final class InterestingThing
{
//definitions
public InterestingThing()
}
public final class MyThing
{
InterestingThing _interestingThing = new InterestingThing();
public MyThing()
}
This is very much the kind of scenario you were describing in your original question, in which the creation of MyThing implies the distinct creation of an InterestingThing. Keep in mind, too this structure is generally forced by the design and definition of the original class of interest.
Ultimately, objects are defined by their classes, and multiply-inherited classes are still just a class, but in a refined, hopefully increasingly robust, hierarchy based on good, incremental object design.
I hope, in some way, this explanation helps to answer your question.
Class A "inherits" Class B. What does this actually mean?
If class A extends class B, it inherits all members (fields and methods) of B, i.e. class A will have these members even through they are not declared in the body of class A.
Whether class A is permitted to access a particular member is an unrelated matter.
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
No. A single object of class A is created. That object just happens to have all inherited members, too. For instance, if you have:
class B {
private int x;
}
class A extends B {
private int y;
}
The runtime will store, for every object of class A, the value of x and the value of y.
That code in class A does not access the value of x is enforced by verifying that the source code of A does not use the name x upon compilation, and by verifying that the bytecode of A does not refer to the field x upon loading the class at runtime. Put differently, access modifiers are independent of memory layout.

When should I use generics to define relationships between types?

Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.
Say I have:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
Should I use:
public class Person{
ICar car;
.
.
public Person (ICar c){
car = c;
}
}
or
public class Person<T extends ICar>{
T car;
.
.
public Person(T c){
car = c;
}
}
or does it depend on the tasks performed?
Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?
A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.
Think about what you try to mimic from the real world, before going into such programming details.
The distinction isn't always clearcut but here are a few clues:
Try to think of them as "type parameters" (Which they are.) They are associated with the class but they're not necessarily related to it. (Look at the collections framework for example.)
Type parameters can only be used if they don't change throughout an object's lifetime. This sounds quite obvious, but it's a very handy rule to decide when NOT to use generics. (Example is a person who can change cars.)
On the other hand, if not many instances will use the type parameter, if it's too optional, that's not a good idea either. (A lot of people might not have cars at all.)
And finally, a general thought that I found really useful: if you're unsure, don't be afraid to prototype it. Write the code both ways and check which one looks simpler and easier to comprehend. Show it to someone else without any explanations or maybe wait a day or two and then re-read the code yourself. Then throw the other one away. Throwing away code is good.
You need the generics version if you have any methods that take or return anything involving a T, or if it's possible for other people to access your car field. (Since you didn't show any methods, we can't really tell.)
For example, with the generics version you can have a method like T someMethod();, then when someone has a Person<Honda>, they know they can get a Honda back when they call someMethod, rather than some unknown type of car if you didn't have generics.
Similarly, with the generics version you can have a method like void anotherMethod(T anotherCar);, then when someone has a Person<Honda>, this forces them to pass a Honda to this method, instead of any car.
So basically, having a generic class allows you to place constraints on uses of the object later on (method calls etc.). If the constructor is the only place that you use T, and you don't need to use T in any methods or fields, then yes, there is no point for it.
This has to do with using Inheritance versus Composition.
Without knowing any other semantics, Composition seems more relevant. A person may change cars, without becoming a different person.
http://www.artima.com/objectsandjava/webuscript/CompoInherit1.html
http://en.wikipedia.org/wiki/Composition_over_inheritance
I'd tend to favor composition (what you're calling dynamic binding), especially in the case you use. A person is not a type of ICar, so using the generics here is kind of weird (to me anyway). I'd use generics as a way of saying "A container for ICar", as in Garage although in that case I might just use a collection type as a variable, or extend the collection type if really needed.
I'd suggest to focus on semantics first:
Providing that you may have a Bmw and a Toyota classes implementing the ICar interface, then make this question: can a Person change his car or would it be a different person if he does so?
The generics approach will force you to create a new Person instance if for some reason you need to change the value of the car attribute from Toyota to Bmw in an existent person instance and thus, this new person will be different from the previous one. Of course, you could create the first Person instance as Person<ICar> instead of hooking it to a specific car class but, why use generics then?

Categories