【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
翻译:缺少方法的返回类型

  • 9
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值