【Java】如何创建一个类

【Java】如何创建一个类

【Java】如何创建一个类

(类学习总结)

1点击最上方菜单栏的文件file,new一个project

2然后点击src创建一个包package

3右键这个包,new一个class

这时候会自动出现一个public class student { }

这时候就创建好一个类了

(有了public class student { }就不用往里面在打一个class了,我糊里糊涂往里面又打了一个class,果然是不行原因好像是因为两个名字一样,不知道要用哪一个)

然后再往里面加东西

类里面包含属性和方法

1.1属性就是类似定义变量

例如:

String Id;

String name;

int age;

上面这些属性就是用来描述学生这个类,写在类的里面。

1.2方法

就是类似C语言函数,是指一些可以完成的功能。

例如:

public void study(){

System.out.println(“我正在学习。”);

}

public void play(){

System.out.println(“我正在玩游戏。”);

}

这个方法是,完成的 study学习和 play游戏的两个功能。

把这些写完直接运行就可以了吗

不是说只有类和方法吗

只写完这些写是不能运行的,但是也不会报错

想要运行还需要进行调用

例如:

public static void main(String[] args) {

// TODO Auto-generated method stub

student stu1=new student();

student stu2=new student();

stu1.study();

stu2.play();

}

解释:

1student stu1=new student();

这里的new是为声明对象分配内存

为什么要分配一个内存,因为声明对象没有内存,(没有内存就创造内存也要上)通过new运算符分配内存。

格式如下:

类名 对象名=new 类名 ;

2 stu1.study();

这个是调用方法

格式如下:

对象名.成员方法

(除了调用方法,还可以调用变量

格式如下:

对象名.成员方法

完整代码

public class student {

/**

* @param args

*/

String Id;

String name;

int age;

public void study(){

System.out.println("我正在学习。");

}

public void play(){

System.out.println("我正在玩游戏。");

}

public static void main(String[] args) {

// TODO Auto-generated method stub

student stu1=new student();

student stu2=new student();

stu1.study();

stu2.play();

}}

写在后面

(弄这个类犯得的错误,有的解决了,有的不知道怎么没有的,写在这里希望有点帮助)

1 Illegal modifier for the local class Cource; only abstract or final is permitted

翻译:本地类Cource的非法修饰符;只允许使用abstract或final

2 The method main cannot be declared static; static methods can only be declared in a static or top level type

翻译:方法main不能声明为static;静态方法只能声明为static或顶级类型

3 Student.stu1 cannot be resolved to a type

翻译:Student.stu1无法解析为类型

4 Return type for the method is missing

翻译:缺少方法的返回类型

相关数据

365提款一周都没到 新车购买多长时间才能在12123备案?
365bet体育官网开户 改革驾培行业 哈哈E学车打造“互联网+驾校”
365提款一周都没到 急用5万块钱哪里能借到?盘点可以快速借到5万的贷款平台