java class example

Example 1: How to make a class in Java?

// Public creates avaliability to all classes/files
public class Object {
  // Instance of a variable per each class created
  public int a = 1;
  // Private restricts in local space (within these brackets)
  private int b = 5;
  
  // Defaults as public
  int c = 0;
  
  // Method Examples
  void setB(int B)
  {
  	b = B;
    // No return b/c 'void'
  }
  int getA()
  {
    return b;
    // Return b/c 'int' in front of method
  }
}

Example 2: java class

public class Lightsaber {
  // properties
  private boolean isOn;
  private Color color;
  
  // constructor
  public Lightsaber(Color color) {
    this.isOn = false;
    this.color = color;
  }
  
  // getters
  public Color getColor() {
    return color;
  }
  public boolean getOnStatus() {
    return isOn;
  }
  
  // setters
  public void turnOn() {
    isOn = true;
  }
  public void turnOff() {
    isOn = false;
  }
}



// Implementation in main method:
public class test {
  public static void main(String[] args) {
    Lightsaber yoda = new Lightsaber(green);
    yoda.turnOn();
  }
}

Example 3: java classes and methods

import java.lang.Math;
import java.util.Scanner;

public class HelloWorld {
  public static void main(String[] args) {
    class ResultNumberShape {

            double number;

            public boolean isSquare(double number) {

                double result = Math.sqrt(number);
                return ((result - Math.floor(result)) == 0);

            }
        }

        ResultNumberShape checkNumber = new ResultNumberShape();

        System.out.println("Enter any number:");
        Scanner scanner = new Scanner(System.in);
        double num = scanner.nextDouble();

        scanner.close();

        if (checkNumber.isSquare(num)) {
            System.out.println(num + " is a sqaure number!");
        } else {
            System.out.println(num + " is not a square!");
        }
    
  }
}

Example 4: how to make a class in java

public class Main {
 public static void main (String[] args) {
	System.out.println("Hello World");
 } 
}

Example 5: using class in java

public class HelloWorld {
  public static void main(String[] args) {
    
    // how to use class in java
    class User{
    	
    	int score;
    }
    
    User dave = new User();
    
    dave.score = 20;
    
    System.out.println(dave.score);
    
 
  }
}

Example 6: java class

//	Example : TestClass (Can be predefined or user-defined)
public class TestClass {
  // properties
  private int id = 111;
  
  // constructor
  public TestClass(){
    super();
  }
  
  // method
  public void test(){
    // some code here
  }
}