In Java, there are two types of data types: primitive data types and reference data types. Primitive data types include int, char, boolean, etc while reference data types include objects and arrays. However, it is also possible to create your own data types in Java through the use of user defined data types.
There are two main types of user defined data types in Java: classes and interfaces. A class is a template that can be used to create objects, while an interface is a set of related methods with empty bodies.
To create a class in Java, you use the “class” keyword followed by the name of the class and a set of curly braces. Within the curly braces, you can define fields (variables) and methods (functions). For example:
public class Dog {
String breed;
int age;
public void bark() {
System.out.println("Woof!");
}
}
To create an object of the class “Dog,” you would use the “new” keyword followed by the name of the class and a set of parentheses. For example:
Dog myDog = new Dog();
You can then access the fields and methods of the object using the dot operator. For example:
myDog.breed = "Labrador";
myDog.age = 5;
myDog.bark();
To create an interface in Java, you use the “interface” keyword followed by the name of the interface and a set of curly braces. Within the curly braces, you define a set of abstract methods (methods without a body). For example:
public interface Animal {
void eat();
void sleep();
}
To implement an interface in a class, you use the “implements” keyword followed by the name of the interface. The class must then provide a body for each of the abstract methods defined in the interface. For example:
public class Cat implements Animal {
public void eat() {
System.out.println("Eating...");
}
public void sleep() {
System.out.println("Sleeping...");
}
}
User defined data types are a powerful feature in Java that allow you to create custom data types that can be used in your programs. They are particularly useful for creating objects that model real-world concepts, such as dogs, cats, and animals in general.
In summary, user defined data types in Java are created using either classes or interfaces. Classes allow you to create objects that have fields and methods, while interfaces define a set of abstract methods that must be implemented in a class. By using user defined data types, you can write code that is more organized, reusable, and easy to understand.