User-defined data types in java
User-defined data types in java
In Java, you can create user-defined data types by defining your own classes. These classes allow you to encapsulate data and behavior into custom data structures. Here's how you can create a user-defined data type in Java:
1. Define a Class: To create a user-defined data type, you need to define a class. The class represents the blueprint or template for objects of that type. Here's a simple example of a Person class:
package Tutorial_01;
public class Person {
// Fields or instance variables
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
1. Create Objects: Once you have defined a class, you can create objects (instances) of that class using the new keyword. For example:
package Tutorial_01;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create Person objects
Person person1 = new Person("Alliya", 35);
Person person2 = new Person("john", 40);
// Access fields and methods
System.out.println(person1.getName()); // Output: Alliya
System.out.println(person2.getAge()); // Output: 40
person1.sayHello(); // Output: Hello, my name is Alliya and I am 35 years old.
}
}
In this example, we've created a Person class with fields (name and age), a constructor to initialize those fields, and methods (getName, getAge, and sayHello) to access and manipulate the data.
By defining your own classes, you can create custom data types that suit your application's specific needs and encapsulate related data and behavior within those classes. This is one of the fundamental principles of object-oriented programming (OOP) in Java.