Reputation: 3
I've been looking at some code and I'm wondering if anyone can explain how this works for example
public class DataTable {
}
Then it is used in another class
public class UsingDatatable {
public DataTable checktables = null;
}
Why does this other class use another class as a variable?
Upvotes: 0
Views: 235
Reputation: 297
Assuming you meant why UsingDataTable class can make instances of DataTable class, there are a number of reasons.
First, DataTable has access to the class. It could be because they share the same package or UsingDataTable 'imports' the DataTable class.
Second, it can be instantiated since it's not final. Thus, each instance(object) inherits all the non-static attributes implemented which could be for some later use.
Third, objects can be constructed from it even if you don't create a constructor in it unless the contsructor is declared private( Java compiler will create by default a public constructor).
Fourth, why a DataTable object is declared as a field in UsingDataTable depends on the implementer. However, in all cases each UsingDataTable object will have its own copy of the checktable field.
Upvotes: 1
Reputation: 23935
This is a has-a relation, also called Composition. In this example, UsingDatatable
has a DataTable
. The following example will help you better understand the concept.
public class Address{
private String houseNo;
private String streetNo;
}
public class Person{
private Address address = null;
}
This example says that the Person
has an Address
.
Upvotes: 1
Reputation: 7457
This is called composition and is aimed at making use of fields and methods of the other class. For more details please take a look at this.
In computer science, object composition is a way to combine simple objects or data types into more complex ones. Compositions are a critical building block of many basic data structures, including the tagged union, the linked list, and the binary tree, as well as the object used in object-oriented programming.
for example :
public class Main {
void aMethod(int a) {
Useful u = new Useful();
int c = u.usefulMethod(Useful.MYCONST, a);
}
}
class Useful {
public final static int MYCONST = 10;
public int usefulMethod(int i, int j) {
return i * j;
}
}
To be more specific about your question (that seems like an example for the notion of object composition), UsingDatatable
is creating an object of the Datatable
to use it (however it seems to be an empty class, but in reality it always contains useful things).
Upvotes: 0
Reputation: 67044
All variables must either:
In your example, checktables
references an instance of the DataTable
class (not the class itself).
Upvotes: 0