Introduction to Object-Oriented Programming in Java
Sani Yusuf
Lead Software Engineering Content Developer
public
can be accessed by object instancesclass Car { // Public property public String color;
// Public constructor public Car(String color){ this.color = color; } }
public class Main {
// main method
public static void main(String[] args) {
Car myCar = new Car("brown");
// Can access public members
// from object instance
System.out.println(
myCar.color); // Brown
}
}
private
can be accessed by object instancesprivate
can only be used within the class// Car class class Car { public String color;
// Private properties private String model;
public Car(String color){ this.color = color; } }
// Main class
public class Main {
// main method
public static void main(String[] args) {
Car myCar = new Car("brown");
// Calling private properties causes errors
System.out.println(
myCar.model); // Java compilation error
}
}
// Car class
class Car {
public String color;
private String model;
public Car(String color){
this.color = color;
}
// Public method
public String getModel(){
return this.model;
}
}
class Car {
// Private method, "calculateSpeed" can only be used within "Car" class private calculateSpeed(){ // Trademarked formula code } public int getSpeed(){ // "calculateSpeed" can be used anywhere within "Car" class return this.calculateSpeed(); } }
static
can be accessed without an object instance
// Formula class
static class Formula {
// Method for calculating square
static int getSquare(int number) {
return number * number;
}
}
// Main class
public class Main {
public static void
main(String[] args) {
// We can use "getSquare"
// without an object instance
System.out.println(
Formula.getSquare(5)); // 25
}
}
public
, private
, static
static
enables the use of classes without creating instancesIntroduction to Object-Oriented Programming in Java