[Java] OOP

Syntax

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Dog {
public String name;
public int weight;
private String gender; // Read Only, can only accessed within the class

// Constructor function
// public Dog(String name, int weight, String gender) {
// this.name = name;
// this.weight = weight;
// this.gender = gender;
// }

// Or use this
public Dog(String nm, int wt, String gen) {
name = nm;
weight = wt;
gender = gen;
}

public void getGender() {
System.out.println(gender);
}

public void Bark() {
System.out.println("WOOF");
}

public void Run() {
System.out.println("RUN");
}
}

public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Xiaoguai", 12, "female");
Dog yourDog = new Dog("Test", 10, "female");

System.out.println(myDog.name);

myDog.Bark();

}
}

Getters and Setters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Ball {
// ...
public String getColor() {
return color;
}

public String getName() {
return name;
}

// Setter
public void setColor(String color) {
this.color = color;
}

public void setName(String name) {
this.name = name;
}
}

Overloading

Overloading allows us to have as many constructors(with different signatures) as we want in a class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Ball {
public Ball() {} // Constructor 1
public Ball(String nm, int wt, String gen) { // Constructor 2
name = nm;
weight = wt;
gender = gen;
}
public Ball(String nm) {
name = nm;
}
}

public class Main {
public static void main(String[] args) {
Ball ball = new Ball();
Ball myBall = new Ball("name", 12, "female");
Ball yourBall = new Ball("yourName");
}
}

Inheritance

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Basketball extends Ball {
public boolean isNBA;
public int capacity;

public int getCapacity() {
return capacity;
}

// Override
public void setName(String newName) {
name = newName + "new";
}
}