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
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}
1public class Main {
2 public static void main (String[] args) {
3 System.out.println("Hello World");
4 }
5}
1// Public creates avaliability to all classes/files
2public class Object {
3 // Instance of a variable per each class created
4 public int a = 1;
5 // Private restricts in local space (within these brackets)
6 private int b = 5;
7
8 // Defaults as public
9 int c = 0;
10
11 // Method Examples
12 void setB(int B)
13 {
14 b = B;
15 // No return b/c 'void'
16 }
17 int getA()
18 {
19 return b;
20 // Return b/c 'int' in front of method
21 }
22}