Anatomy of Java
My learning of java basics and OOP structure
- Basic Java Class
- Methods
- Class Attributes with Objects
- Constructors
- Getters and Setters
- Dessert Example
// Main Class. Name of class needs to be the same as filename
public class Hello {
// The main method. First thing program does is find this method and run it
public static void main(String[] args) {
System.out.println("Hello");
}
}
Hello.main(null);
// Calls main method with passing nothing for parameter
public class Sports {
// Method called sportIntro. Similar to functions in python
static void sportIntro() {
System.out.println("I love sports");
}
public static void main(String[] args) {
// calls method/function
sportIntro();
}
}
Sports.main(null);
public class Sports {
// attributes of the class Sports
String name;
double population;
public static void main(String[] args) {
// Creating new object called basketball
Sports basketball = new Sports();
// setting attributes for the object basketball
basketball.name = "Basketball";
basketball.population = 24.23; // in millions
System.out.println("For the game of " + basketball.name + ", " + basketball.population + " million people play!");
}
}
Sports.main(null);
public class Sports {
String name;
// constructor for the class Sports. Needs to be same name as class
public Sports(String title) {
name = title;
}
public static void main(String[] args) {
Sports basketball = new Sports("Basketball is the best sport");
System.out.println(basketball.name);
}
}
Sports.main(null);
public class Sports {
// can only be changed with a setter
private String title;
// returns private variable information
public String getTitle() {
return title;
}
// only thing that can change the private variable title
public void setTitle(String title) {
this.title = title;
}
}
public class Main {
public static void main(String[] args) {
Sports basketball = new Sports();
basketball.setTitle("basketball");
System.out.println(basketball.getTitle());
}
}
Main.main(null);
public class Desserts {
// setting class attributes that can only be accessed with setter/getter
private String name;
private int price;
// intiailize variables in constructor
public Desserts() {
name = "dessert";
price = 5;
}
// setter method
public void setDesc(String name, int price) {
System.out.println("In Setter");
this.name = name;
this.price = price;
}
// getter method
public String getDesc() {
return "The name of the dessert is " + this.name + " and the price is $" + this.price;
}
public static void main(String[] args) {
Desserts Dessert1 = new Desserts();
Dessert1.setDesc("Cake", 10);
System.out.println(Dessert1.getDesc());
}
}
Desserts.main(null);