#Classes, constructors and access modifiers
AddedA Java class will look familiar from TypeScript: fields, a constructor, methods, this, private. TypeScript borrowed much of its class syntax from Java and C#. The differences are in the details, and they matter:
- Fields are declared with their types in the class body, and every field has a default (
0,false,null) until a constructor sets it. There are no parameter properties (constructor(private name: string)); you assignthis.name = nameyourself. - The constructor is named after the class, and a class can have several constructors with different parameters (overloading). One constructor can call another with
this(...). TypeScript has one constructor and optional parameters instead. - Access modifiers are enforced by the compiler and the JVM. TypeScript's
privatedisappears when the code is compiled to JavaScript (only#privatesurvives at run time). Java'sprivateis still there in the bytecode, and the JVM refuses access from other classes. - There are four access levels, not three. Leaving the modifier off doesn't mean public: it means package-private, visible only to classes in the same package.
| Modifier | Same class | Same package | Subclass in another package | Everywhere |
|---|---|---|---|---|
private | yes | no | no | no |
| (none): package-private | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
The mental model: a package is a team, and package-private is "internal to the team". Classes in the same package cooperate freely; everyone else sees only what you mark public. That's why well-organised Java code keeps most helper classes package-private and exposes a small public surface, the way a Node package exposes only what its index.js exports.
package com.example.bank;
public class Account {
private final String owner;
private long balanceInCents;
String branch = "Leeds"; // no modifier: package-private
public Account(String owner) {
this(owner, 0); // calls the other constructor
}
public Account(String owner, long openingCents) {
if (openingCents < 0) {
throw new IllegalArgumentException("opening balance can't be negative");
}
this.owner = owner;
this.balanceInCents = openingCents;
}
public void deposit(long cents) {
if (cents <= 0) {
throw new IllegalArgumentException("deposit must be positive");
}
balanceInCents += cents;
}
public long balance() {
return balanceInCents;
}
public String owner() {
return owner;
}
}package com.example.bank;
public class Audit {
public static String describe(Account account) {
return account.owner() + " banks at " + account.branch; // same package: allowed
}
}package com.example.app;
import com.example.bank.Account;
import com.example.bank.Audit;
public class Main {
public static void main(String[] args) {
var account = new Account("Rohit", 10_000);
account.deposit(2_550);
System.out.println(account.owner() + ": " + account.balance() + " cents");
System.out.println(Audit.describe(account));
var empty = new Account("Maya");
System.out.println(empty.owner() + ": " + empty.balance() + " cents");
}
}$ javac -d out com/example/bank/Account.java com/example/bank/Audit.java com/example/app/Main.java
$ java -cp out com.example.app.Main
Rohit: 12550 cents
Rohit banks at Leeds
Maya: 0 centsAccounthas two constructors.new Account("Rohit", 10_000)picks the two-argument one by its parameter types; it validates the opening balance and sets both fields. (10_000is just10000: underscores in number literals are allowed since Java 7.)new Account("Maya")picks the one-argument constructor, which immediately callsthis(owner, 0), so the validation lives in one place. The balance prints as0 cents.ownerisprivate final: set once in the constructor and readable only through theowner()method.balanceInCentsisprivateand only changes throughdeposit, which refuses non-positive amounts. That's encapsulation: the class guarantees its own rules.deposit(2_550)takes the balance from 10,000 to 12,550, printed asRohit: 12550 cents.branchhas no modifier, so it's package-private.Auditis in the same package,com.example.bank, so it can readaccount.branchdirectly:Rohit banks at Leeds.Main, incom.example.app, can't (see the next example).- The accessors are named
owner()andbalance(), the style records use. Older code and many frameworks use the JavaBeans style,getOwner()andgetBalance(); you'll see both, and many codebases generate them with the Lombok library.
package com.example.app;
import com.example.bank.Account;
public class Snoop {
public static void main(String[] args) {
var account = new Account("Rohit");
System.out.println(account.branch);
account.balanceInCents = 1_000_000;
}
}$ javac -cp out -d out com/example/app/Snoop.java
com/example/app/Snoop.java:8: error: branch is not public in Account; cannot be accessed from outside package
System.out.println(account.branch);
^
com/example/app/Snoop.java:9: error: balanceInCents has private access in Account
account.balanceInCents = 1_000_000;
^
2 errorsSnooplives incom.example.app, so it's outsideAccount's package. It's compiled against the classes already inout(-cp out).- Reading
account.branchfails: package-private means invisible outsidecom.example.bank, and the message says exactly that. - Writing
account.balanceInCentsfails too: it'sprivatetoAccount. - Both errors are compile-time, and nothing is produced. In TypeScript,
privategives the same kind of error, but(account as any).balanceInCents = 1_000_000would get through and work at run time. In Java there's no such cast that gets around the check; only reflection (setAccessible) can reach private members, and that's a deliberate, visible act.