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
1public class Puppy {
2 public Puppy(String name) {
3 // This constructor has one parameter, name.
4 System.out.println("Passed Name is :" + name );
5 }
6
7 public static void main(String []args) {
8 // Following statement would create an object myPuppy
9 Puppy myPuppy = new Puppy( "tommy" );
10 }
11}
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.
1public class Main {
2 int x = 5;
3
4 public static void main(String[] args) {
5 Main myObj = new Main();
6 System.out.println(myObj.x);
7 }
8}
9
10