用Java编写任何代码时,都需要遵循一组特定的规则和规定,这被视为标准。例如-一个类包含变量和函数。这些功能可用于处理变量。可以扩展课程,也可以即兴创作。
List of packages that are imported;
public class <class_name>
{
Constructor (can be user defined or implicitly created)
{
Operations that the constructor should perform;
}
Data elements/class data members;
User-defined functions/methods;
public static void main (String args[]) extends exception
{
Instance of class created;
Other operations;
}
}Java程序的执行从“ main”功能开始。由于它不返回任何内容,因此其返回类型为void。该代码应该可以访问它,因此它是“公共的”。
构造函数用于初始化先前定义的类的对象。不能使用关键字“最终”,“抽象”或“静态”或“同步”来声明它们。
另一方面,用户定义的功能可以执行特定任务,并且可以与关键字“ final”,“ abstract”或“ static”或“ synchronized”一起使用。
public class Employee
{
static int beginning = 2017;
int num;
public Employee(int i)
{
num = i;
beginning++;
}
public void display_data()
{
System.out.println("The static value is : " + beginning + "\n The instance value is :"+ num);
}
public static int square_val()
{
return beginning * beginning;
}
public static void main(String args[])
{
Employee emp_1 = new Employee(2018);
System.out.println("First object created ");
emp_1.display_data();
int sq_val = Employee.square_val();
System.out.println("The square of the number is : "+ sq_val);
}
}输出结果
First object created The static value is : 2018 The instance value is :2018 The square of the number is : 4072324
名为Employee的类具有不同的属性,并且定义了一个构造函数,该构造函数使该类的属性之一递增。名为'display_data'的函数显示类中存在的数据。另一个名为'square_val'的函数返回特定数字的平方。在main函数中,将创建该类的实例并调用这些函数。相关输出将显示在控制台上。