Can I call a class have only instance variable a wrapper class? - java

I have a class which only contains instance variables, getter and setters, something like:
public class MyClass {
#Getter #Setter private String bla;
#Getter #Setter private String blabla;
#Getter #Setter private Date dateBla;
}
Can I call it a Wrapper-class? Or do such classes have a specific name? So far I am only familiar with primitive wrapper classes.

Wrapper class is definitely the wrong term.
More correct terms would be:
Model class or Domain Model, if it's used to represent from the underlying domain in the system but note that it's also likely an example of the anemic domain model antipattern.
Data Tansfer Object if the reason it contains no functionality is that it mainly exists to move data.
Java Bean to stress that it conforms to that convention, but that's not entirely correct, as a JavaBean is allowed to have other methods.
Value Object, the misuse of a term for something else that occurred in a popular book (Core J2EE Patterns) and, although corrected in later editions, keeps popping up.

No, you can't call it a wrapper class. A wrapper class sits on top of the main class / primitive and provides additional features.
For example Integer class is a wrapper over the primitive int because it provides additional functionality when compared to what an int provides. It also provides additional behavioral properties (like the ability to be inserted into collections).
Your class is just a plain java class.

As per http://way2java.com/java-lang/wrapper-classes/
As the name says, a wrapper class wraps (encloses) around a data type
and gives it an object appearance. Wherever, the data type is required
as an object, this object can be used. Wrapper classes include methods
to unwrap the object and give back the data type. It can be compared
with a chocolate. The manufacturer wraps the chocolate with some foil
or paper to prevent from pollution. The user takes the chocolate,
removes and throws the wrapper and eats it.
[1]: http://way2java.com/java-lang/wrapper-classes/
Generally speaking, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. So no you can't call the class mentioned in the question a wrapper class.

Related

Why is a class called an abstraction of an object?

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.

Will objects of a custom class, inside an array, keep their data after serialization?

I am building a small application for keeping statistical data of some sort. I have a general question, before I start coding hard in this matter.
Say we have an object X of its own class, representing a sports match. It has several fields, among which is another object Y - also it's own class. Y will represent stats for a given game. The structure should be something like:
class Match {
Date date;
String venue;
ArrayList<Game>[10] gameList;
...
}
class Game{
int result;
int blah blah;
...
}
If I go and create a couple of Match objects, stored in an array for example, i can serialize an object, that contains this array of Matches, but when i deserialize it back, will I be able to keep the data inside the Game objects for example? Do I need to make each class used Serializable?
The reason for my worries are those lines from the JAVA Api Documentation:
During deserialization, the fields of non-serializable classes will
be initialized using the public or protected no-arg constructor of the
class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored
from the stream.
When traversing a graph, an object may be encountered that does not
support the Serializable interface. In this case the
NotSerializableException will be thrown and will identify the class of
the non-serializable object.
Yes, you need to make Match class serializable. Making a class serialize means that you need to make all instance variables of that class serializable too (notice the recursive definition). In your example, to make Match class serializable, you need to make Game class serializable.
i guess the term
non-serializable classes
means such class doesn't implements the serializable interface there's exist classes in java doesn't implement serializable interface and you can't serialize them for example java.awt.BasicStroke you can't serialize any instance of of this class directly

why attribute from interface is declared in classes

I have seen that if I have interface named interfaceABC.
Example:
public class ABController extends AbstractCOntroller {
private interfaceABC inter;
I am confused that why we make object from interface not from class that implemented it.
private interfaceABC inter;
i am confused that why we make object from interface not from class that implemented it
We haven't created an object/instance yet. We simply declared a variable to hold it. We don't make objects from interfaces (you have to use a concrete class to do that), but we will often use interface types instead of the actual concrete class for variable declarations, method parameter types, and method return types.
Take this for exmaple:
List<Example> examples = new ArrayList<Example>();
...
public List<Example> getExamples() { return examples; }
Using the interface List here instead of the concrete class ArrayList follows a common best practice: to use interfaces instead of concrete classes whenever possible, e.g. in variable declarations, parameters types, and method return types. The reason this is considered a best practice is:
Using the interface for declarations and for return types hides an implementation detail, making it easier to modify in the future. For example, we may find that the code works better using a LinkedList rather than ArrayList. We can easily make this change in one place now, just where the list is instantiated. This practice is especially key for method parameter types and method return types, so that external users of the class won't see this implementation detail of your class and are free to change it without affecting their code.
By using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an ArrayList. If this class relied on some ArrayList-specific property, i.e. it needs to use an ArrayList method, than using ArrayList<Example> examples = ... instead of List<Example> examples = ... may be a hint that this code relies on something specific to an ArrayList.
It may simplify testing/mocking to use the more abstract List than to use the concrete class ArrayList.
We haven't made an object, we've made a reference.
By using a reference to the interface rather than a concrete class, we are free to swap in a different implementation of the interface, with no changes to this code. This improves encapsulation, and also facilitates e.g. testing (because we can use mock objects). See also dependency injection.
This is actually very useful. Take the example that we're using a list.
public class A {
private List<String> list;
public A(List<String> list) {
this.list = list;
}
}
This allows class A to work with all operations defined by the list interface. The class constructing A can now give any implementation without changing the code of class A, hence promoting encapsulation, code reuse, testing etc. For instance:
new A(new ArrayList<String>());
For a private field, it does not really matter too much, as that's an implementation detail anyway. Many people will still on principle use the interface everywhere they can.
On the other hand, protected fields (and of course the parameters of public methods) form an API that becomes much more flexible by using interfaces, because that allows subclasses/clients to choose which implementation class they want to use, even classes they supply themselves and which didn't even exist when the API was created.
Of course, if you have a public set method or constructor that sets the private field, then you have to use the interface type for the field as well.
Imagine a gift-wrapping stall in a shop that has a machine which will wrap any box.
The machine is simply designed and built to wrap a rectangular box, it shouldn't matter whether there's chocolate in the box or a toy car. If it mattered, the machine would quite obviously be flawed.
But even before you get to that stall, you have to buy that gift: so the cashier scans the barcode first. The barcode scanner is another example of the same principle: it will scan anything as long as it has a recognisable barcode on it. A barcode scanner that only scanned newspapers would be useless.
These observations led to the concept of encapsulation in software design, which you can see in action when a class refers to an object by an interface only, and not its concrete class.

Class object in Objective C

I am coming from Java to Objective C, and the idea of a class object has me wondering about similarities with Java. From the Objective C guide in Apple documentation:
A class definition's information is compiled and recorded in data structures made available to the runtime systems. The compiler creates just one object, a class object, to represent the class.
So my understanding is that the class object is created for all classes that are going to be used by the program, and a class object is what is used to create objects for that class.
For comparison, does the JVM have a similar object for all classes it loads?
Given that Java was derived directly from Objective-C (no, really, it was), the runtime models of the two are quite similar.
In Java, the notion of a "Class" isn't quite as generic as it is in Objective-C.
In Objective-C, a Class is an instance of what is known as the metaclass. For all intents and purposes, each Class object in Objective-C does exactly as you say; it describes a particular class available in the Objective-C runtime.
The same is conceptually true of Java classes. There is one key difference. In Objective-C, class methods are inherited across subclasses and more significantly a subclass can override a superclass's class method(s).
For example, the NSArray class implements the +array class method (the '+' means "class method"). The NSMutableArray subclass of NSArray overrides +array to return a mutable instance instead.
java.lang.Class is more akin to the Objective-C runtime API; it is the mechanism via which you introspect the classes available in the runtime. Since Java doesn't have functional API, the API is wrapped up in an appropriately named class. java.lang.Class is kinda the runtime API and the metaclass all in one.
A comparable structure in Java would be java.lang.Class.
I think there is a class object for each class.
That class object is the one that, at low level, is used for functions as class_getName(), class_getSuperclass(), class_getVersion(), class_respondsToSelector(). If there would be a single class object for all the classes, then those functions would return the same result for all the classes.

What is the difference between a JavaBean and a POJO?

I'm not sure about the difference. I'm using Hibernate and, in some books, they use JavaBean and POJO as an interchangeable term. I want to know if there is a difference, not just in the Hibernate context, but as general concepts.
A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.
A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.
All JavaBeans are POJOs but not all POJOs are JavaBeans.
A JavaBean is a Java object that satisfies certain programming conventions:
the JavaBean class must implement either Serializable or Externalizable;
the JavaBean class must have a public no-arg constructor;
all JavaBean properties must have public setter and getter methods (as appropriate);
all JavaBean instance variables should be private.
According to Martin Fowler a POJO is an object which encapsulates Business Logic while a Bean (except for the definition already stated in other answers) is little more than a container for holding data and the operations available on the object merely set and get data.
The term was coined while Rebecca Parsons, Josh MacKenzie and I were
preparing for a talk at a conference in September 2000. In the talk we
were pointing out the many benefits of encoding business logic into
regular java objects rather than using Entity Beans. We wondered why
people were so against using regular objects in their systems and
concluded that it was because simple objects lacked a fancy name. So
we gave them one, and it's caught on very nicely.
http://www.martinfowler.com/bliki/POJO.html
Pojo - Plain old java object
pojo class is an ordinary class without any specialties,class totally loosely coupled from technology/framework.the class does not implements from technology/framework and does not extends from technology/framework api that class is called pojo class.
pojo class can implements interfaces and extend classes but the super class or interface should not be an technology/framework.
Examples :
1.
class ABC{
----
}
ABC class not implementing or extending from technology/framework that's why this is pojo class.
2.
class ABC extends HttpServlet{
---
}
ABC class extending from servlet technology api that's why this is not a pojo class.
3.
class ABC implements java.rmi.Remote{
----
}
ABC class implements from rmi api that's why this is not a pojo class.
4.
class ABC implements java.io.Serializable{
---
}
this interface is part of java language not a part of technology/framework.so this is pojo class.
5.
class ABC extends Thread{
--
}
here thread is also class of java language so this is also a pojo class.
6.
class ABC extends Test{
--
}
if Test class extends or implements from technologies/framework then ABC is also not a pojo class because it inherits the properties of Test class.
if Test class is not a pojo class then ABC class also not a pojo class.
7.
now this point is an exceptional case
#Entity
class ABC{
--
}
#Entity is an annotation given by hibernate api or jpa api but still we can call this class as pojo class.
class with annotations given from technology/framework is called pojo class by this exceptional case.
POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO
JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.
All Javabeans are POJOs but all POJO are not Javabeans
Java beans are special type of POJOs.
Specialities listed below with reason
In summary: similarities and differences are:
java beans: Pojo:
-must extends serializable -no need to extends or implement.
or externalizable.
-must have public class . - must have public class
-must have private instance variables. -can have any access specifier variables.
-must have public setter and getter method. - may or may not have setter or getter method.
-must have no-arg constructor. - can have constructor with agruments.
All JAVA Beans are POJO but not all POJOs are JAVA Beans.
POJOS with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS.
You've seen the formal definitions above, for all they are worth.
But don't get too hung up on definitions.
Let's just look more at the sense of things here.
JavaBeans are used in Enterprise Java applications, where users frequently access data and/or application code remotely, i.e. from a server (via web or private network) via a network. The data involved must therefore be streamed in serial format into or out of the users' computers - hence the need for Java EE objects to implement the interface Serializable. This much of a JavaBean's nature is no different to Java SE application objects whose data is read in from, or written out to, a file system.
Using Java classes reliably over a network from a range of user machine/OS combinations also demands the adoption of conventions for their handling. Hence the requirement for implementing these classes as public, with private attributes, a no-argument constructor and standardised getters and setters.
Java EE applications will also use classes other than those that were implemented as JavaBeans. These could be used in processing input data or organizing output data but will not be used for objects transferred over a network. Hence the above considerations need not be applied to them bar that the be valid as Java objects. These latter classes are referred to as POJOs - Plain Old Java Objects.
All in all, you could see Java Beans as just Java objects adapted for use over a network.
There's an awful lot of hype - and no small amount of humbug - in the software world since 1995.
All Pojo(s) are JavaBean(s), but not the opposite.
What is POJO?
A POJO has no naming convention for properties or methods. We don't follow any real convention for constructing, accessing, modifying the class's state.
Example:
public class Pojo {
public String firstname;
public String LASTName;
public String name() {
return this.firstname + " " + this.LASTName;
}
}
here, I could have replaced firstname by first_name or Firstname or by any noun and the same with the variable LASTName.
The term has most likely gained widespread acceptance because of the
need for a common and easily understood term that contrasts with
complicated object frameworks.[2]
Reflection using POJO.
it may limit a framework's ability to favor convention over configuration, understand how to use the class, and augment its functionality.[1]
List<String> propertyNames =
Arrays.stream(PropertyUtils.getPropertyDescriptors(Pojo.class))
.map(PropertyDescriptor::getDisplayName)
.collect(Collectors.toList());
System.out.println(propertyNames);
If we use Third Party Libraries PropertyUtils for reflection we may face issues, as this will result in
[]
What is Java Beans?
A JavaBean is still a POJO but introduces a strict set of rules around
how we implement it:
Access levels – our properties are private and we expose getters and setters.
Method names – our getters and setters follow the getX and
setX convention (in the case of a boolean, isX can be used for a
getter)
Default Constructor – a no-argument constructor must be
present so an instance can be created without providing arguments, for
example during deserialization
Serializable – implementing the Serializable interface allows us to store the state.
Example:
#Getter
#Setter
class Pojo implements Serializable {
public String firstName;
public String lastName;
}
Reflection using Java Bean.
If we again use third party Libraries such as `PropertyUtils` for reflection the result will be different
[firstName,lastName]

Categories