Java Classes and Objects
Java is an object-oriented language. You describe things with classes and create real copies of them called objects.
What are Classes and Objects?
A class is a plan or template. An object is a real thing made from that plan.
| Class | Objects |
|---|---|
| Student | Ali, Ayesha, Bilal |
| Car | A white Mehran, a red Civic |
| Product | Rice bag, cooking oil, tea pack |
A class has fields (data, also called attributes) and methods (actions).
Creating a Class and an Object
Example
class Student {
String name;
int marks;
void introduce() {
System.out.println("I am " + name + " and I got " + marks + " marks");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Ali";
s1.marks = 82;
Student s2 = new Student();
s2.name = "Ayesha";
s2.marks = 95;
s1.introduce();
s2.introduce();
}
}I am Ali and I got 82 marks I am Ayesha and I got 95 marks
The new keyword creates an object. Each object has its own copy of the fields.
Constructors
A constructor is a special method that runs when an object is created. It has the same name as the class and no return type. Use it to set starting values:
Example
class Product {
String name;
int price;
Product(String name, int price) {
this.name = name;
this.price = price;
}
void show() {
System.out.println(name + ": Rs " + price);
}
}
public class Main {
public static void main(String[] args) {
Product tea = new Product("Tea pack", 450);
Product rice = new Product("Rice 5kg", 1800);
tea.show();
rice.show();
}
}Tea pack: Rs 450 Rice 5kg: Rs 1800
this.name means "the field of this object", so Java can tell it apart from the parameter name.
Encapsulation: private Fields
It is good practice to make fields private so other code cannot change them in a wrong way. Give access through getter and setter methods:
Example
class BankAccount {
private int balance = 0;
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
public int getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(5000);
acc.deposit(-100); // ignored
System.out.println(acc.getBalance());
}
}5000
Access Modifiers
| Modifier | Who can use it |
|---|---|
public | Any class |
private | Only the same class |
protected | The same package and child classes |
| (none) | Only classes in the same package |
Inheritance in One Look
A class can extend another class and reuse its fields and methods:
Example
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Cat extends Animal {
void meow() { System.out.println("Meow"); }
}
// new Cat() can call both eat() and meow()The four big ideas of OOP are encapsulation, inheritance, polymorphism and abstraction. Start with classes, objects and constructors; the rest builds on them.
Exercise
Exercise
Which keyword creates a new object from a class?
