how to write a class code example
Example 1: 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 2: 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
}
}
Example 3: how to make a new class
#Use the class function and give the class a name
#next use the def __init__() to initilaize and give it some properties.
class Fruits():
def __init__(self, name, colour, taste):
self.name = name
self.colour = colour
self.taste = taste
#Now create an object by first calling the class
fruit1 = Fruits(apple, red, sweet)
print(fruit1.name)
#this will print the name which is apple
print(fruit1.colour)
#this will print the colour which is red
print(fruit1.taste)
#this will print the taste which is sweet