Java程序的结构和成员
编写任何 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。它应该可以被代码访问,因此它是 ‘public’。
构造函数用于初始化先前定义的类的对象。它们不能用关键字 ‘final’、‘abstract’、‘static’ 或 ‘synchronized’ 声明。
另一方面,用户定义的函数执行特定任务,并且可以使用关键字 ‘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 函数中,创建类的实例并调用函数。相关的输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP