Define and use composite data types
13.1 User‑Defined Data Types 📦
What is a User‑Defined Data Type?
A user‑defined data type (UDT) lets you bundle several related values together into a single logical unit. It’s like creating your own LEGO set: you decide which bricks (values) belong together and how they’re connected.
Why Use Composite Data Types?
- Organises code – keeps related data together.
- Improves readability – a
Studenttype is clearer than separatename,age,gradevariables. - Encourages re‑use – the same type can be used in many places.
Defining a Composite Data Type in Java
In Java, a composite data type is usually defined with a class or record. Below is a simple class that represents a book.
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
// Getters
public String getTitle() { return title; }
public String getAuthor() { return author; }
public int getPages() { return pages; }
}
If a Book has 3 fields, its size is:
$$|Book| = |title| + |author| + |pages|$$
Using the Data Type
- Create an instance:
Book myBook = new Book("1984", "George Orwell", 328); - Access its data:
String title = myBook.getTitle(); - Store many books in an array or
ArrayListfor collections.
Exam Tip Box 🎯
Tip: When the question asks you to define a data type, include:
- Field names and types
- Constructor(s)
- Getter methods (or public fields if allowed)
record types, remember the concise syntax: record Point(int x, int y) {}.
Example: Contact Record
| Field | Type | Description |
|---|---|---|
| name | String | Full name of the person |
| phone | String | Telephone number |
| String | Email address |
Quick Recap
- UDTs bundle related data.
- Define with
classorrecord. - Include fields, constructor, and access methods.
- Use in collections for multiple instances.
Remember: A well‑designed data type is like a well‑built LEGO set – it’s easy to use, easy to understand, and can be reused in many projects. 🚀
Revision
Log in to practice.
3 views
0 suggestions