以类的方式组织代码,以对象的组织(封装)数据
//方法的定义
//Demo01 class修饰的类,每个类里都有main方法
public class Demo01 {
public static void main(String[] args) {
}
//public修饰符,公共的,所有人可访问的方法 String返回值类型 sayHello方法名 (参数)
public String sayHello(){
return "hello,world";//看到return代表方法结束,返回一个结果
}
public void hello(){
return;//void
}
public int max(int a,int b){//形式参数
return a>b?a:b;//三元运算符
}
public void readFile(String file) throws IOException{//异常:throws IOException
}
}
回顾方法的定义和调用
public class Demo02 {
public static void main(String[] args) {
//静态方法static
Student.say();//类名.方法名
// 非静态方法
Student student = new Student();//没有static要new来实例化这个类 new Student()+alt+回车
//对象类型 对象名 =对象值
student.say2();//调用
}
//加static和类一起加载,调用不存在东西会报错
public static void a (){
b();
}
//类实例化后才存在
public void b (){
}
}
//学生类
public class Student {
//方法
public static void say(){//静态方法
System.out.println("学生说话了");
}
public void say2(){//非静态方法
System.out.println("学生说话了1");
}
}
public class Demo03 {
public static void main(String[] args) {
int add = Demo03.add(1, 2);//实际参数和形式参数类型要对应
System.out.println(add);
}
public static int add(int a,int b){//无static则调用 new Demo03().add()
return a+b;
}
}
public class Demo04 {
//值传递
public static void main(String[] args) {
int a=1;
System.out.println(a);//1
Demo04.change(a);
System.out.println(a);//1
}
public static void change(int a){//返回值为空
a=10;
}
}
public class Demo05 {
//引用传递,对象,本质还是值传递
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);//null
Demo05.change(person);
System.out.println(person.name);//征途
}
public static void change(Person person){//返回值为空
person.name="征途";//person是个对象,指向Person person = new Person();这是一个具体的人,可改变属性
}
}
//定义了Person类,有一个属性:name
class Person{
String name;//默认null
}
类与对象的创建
//学生类,类只包括属性和方法
public class Student {
//属性:字段
String name;//null
int age;//0
//方法
public void study(){
System.out.println(this.name+"在学习");//this当前这个类
}
}
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
//类是抽象的,需要实例化
Student xiaoming = new Student();//类实例化后返回一个自己的对象
Student xiaohong = new Student();//小明小红是一个类的不同对象
xiaoming.name="小明";
xiaoming.age=3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
System.out.println(xiaohong.name);
System.out.println(xiaohong.age);
}
}


