1public class Lightsaber {
2 // properties
3 private boolean isOn;
4 private Color color;
5
6 // constructor
7 public Lightsaber(Color color) {
8 this.isOn = false;
9 this.color = color;
10 }
11
12 // getters
13 public Color getColor() {
14 return color;
15 }
16 public boolean getOnStatus() {
17 return isOn;
18 }
19
20 // setters
21 public void turnOn() {
22 isOn = true;
23 }
24 public void turnOff() {
25 isOn = false;
26 }
27}
28
29
30
31// Implementation in main method:
32public class test {
33 public static void main(String[] args) {
34 Lightsaber yoda = new Lightsaber(green);
35 yoda.turnOn();
36 }
37}
38
1// this might help you understand how classes work
2public class MathTest {
3
4 public static void main(String[] args) {
5
6 class MathAdd {
7
8 int num1;
9 int num2;
10
11 public int addNumbers() {
12
13 int addThemUp = num1 + num2;
14 return addThemUp;
15 }
16 }
17
18 MathAdd addition = new MathAdd(); // create a new instance of the class
19
20 // you can access variables from the class
21 addition.num1 = 10;
22 addition.num2 = 20;
23
24 // and use the method from the class to add them up
25 System.out.println(addition.addNumbers());
26
27 }
28}
1
2public class HelloWorld {
3 public static void main(String[] args) {
4
5 // how to use class in java
6 class User{
7
8 int score;
9 }
10
11 User dave = new User();
12
13 dave.score = 20;
14
15 System.out.println(dave.score);
16
17
18 }
19}
20
1Class is a blueprint or template which
2you can create as many objects as you
3like. Object is a member or instance
4of a class.
5Class is declared using class keyword,
6Object is created through
7new keyword mainly. A class is a template
8 for objects. A class defines
9object properties including a valid range
10 of values, and a default value.
11A class also describes object behavior.
1// Example : TestClass (Can be predefined or user-defined)
2public class TestClass {
3 // properties
4 private int id = 111;
5
6 // constructor
7 public TestClass(){
8 super();
9 }
10
11 // method
12 public void test(){
13 // some code here
14 }
15}
1class Dog {
2 int age = 5;
3
4 public static void main(String[]args) {
5
6 Dog myObj = new Dog();
7 System.out.println(myObj.age);
8 }
9}