java class c = new class() code example
Example 1: classes in java
// this might help you understand how classes work
public class MathTest {
public static void main(String[] args) {
class MathAdd {
int num1;
int num2;
public int addNumbers() {
int addThemUp = num1 + num2;
return addThemUp;
}
}
MathAdd addition = new MathAdd(); // create a new instance of the class
// you can access variables from the class
addition.num1 = 10;
addition.num2 = 20;
// and use the method from the class to add them up
System.out.println(addition.addNumbers());
}
}
Example 2: using class in java
public class HelloWorld {
public static void main(String[] args) {
// how to use class in java
class User{
int score;
// method that can be used outside the class
public boolean hasWon(){
if(score >= 100){
return true;
} else {
return false;
}
}
}
User dave = new User();
dave.score = 20;
System.out.println(dave.hasWon());
}
}