Fields (Attributes)
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 6 of 87.
Fields (attributes) are variables that store data inside a class. They are usually private and accessed through getter and setter methods.
Declaring fields
public class Person {
private String name;
private int age;
}Adding getters and setters
public class Person {
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
}Using the class
Person person = new Person();
person.setName("Alice");
person.setAge(25);
System.out.println(person.getName()); // AliceMaking fields private is called encapsulation. It protects data by controlling access through methods, allowing you to add validation in setters.
Challenge
MediumCreate a BankAccount class with private fields and getter methods:
- Private fields:
accountName(String) andbalance(double) - A constructor to set both fields
- Getter methods for each field
deposit()method to add moneywithdraw()method that returns "Success" or "Insufficient funds"
Cheat sheet
Fields (attributes) are variables that store data inside a class. They are usually private and accessed through getter and setter methods.
Declaring private fields:
public class Person {
private String name;
private int age;
}Adding getters and setters:
public class Person {
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
}Using the class:
Person person = new Person();
person.setName("Alice");
person.setAge(25);
System.out.println(person.getName()); // AliceMaking fields private is called encapsulation. It protects data by controlling access through methods, allowing you to add validation in setters.
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
double initial = Double.parseDouble(scanner.nextLine());
double deposit = Double.parseDouble(scanner.nextLine());
BankAccount account = new BankAccount(name, initial);
System.out.println("Account: " + account.getAccountName());
System.out.println("Balance: " + account.getBalance());
account.deposit(deposit);
System.out.println("After deposit: " + account.getBalance());
String result = account.withdraw(2000);
System.out.println("Withdraw 2000: " + result);
System.out.println("Final Balance: " + account.getBalance());
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System