1.类和对象
1.1类的语法格式
public class 类 {
特征(Java中的变量)
行为(java 中暂时不带static的方法)
}
1.2创建对象
1.先有类才能有对象
2.对象的创建必须在main主函数中
对象创建的语法格式:
类 对象的名字= new 类(); Dog dog1 = new Dog();
2.创建类和带有main主函数的类可以写在一个文件中
写的类和带有main主函数 不在同一个文件中,分开写的
但是也可以写在用一个Java文件中。新建的文件的名字应该是 测试类类名
1.创建类
一个类 现在所学的是由属性和方法组成的
calss Person {
String name;
int age;
//行为 在Java中 用方法表示行为
public void eat () {
sout("");
}
}
2.创建对象
由类衍生出来的 具体的实体 模板 ==》 类
暂时在main主函数中 创建对象
类 对象的名字 = new 类();
对象.属性 = 值;
3.创建类和带有main主函数的类写在同一个文件中写法
3.构造方法
3.1无参构造方法
语法格式:
public 类名 () {
语句体
}
class People {
//属性
String name;
int age;
//定义一个无参构造方法
public People () {
System.out.println("嘻嘻");
//this 当前对象
name = "狗蛋";
age = 12;
}
}
public class Demo4 {
public static void main(String[] args) {
//依靠构造方法去创建 对象
People people = new People();
people.name = "二狗";
people.age = 22;
System.out.println(people.name);//
System.out.println(people.age);//
People people2 = new People();
}
}
3.2有参构造方法
语法格式:
public 类名 (参数) {
}
public Person (String name, int age) {
this.name = name;
this.age = age;
}
class Cat {
String name;
int age;
char sex;
//一旦在类中写了有参构造方法,默认无参构造方法就不在了
//有参构造方法 是特殊的方法
public Cat (String name, int age, char sex) {
//this 代表是当前对象
//this.name 当前对象的name属性
this.name = name;
this.age = age;
this.sex = sex;
}
}
public class Demo6 {
public static void main(String[] args) {
//创建对象和构造方法有关系, new Cat(); 依靠类中无参构造方法
Cat cat = new Cat("二虎", 1, '公')
cat.name = "二牛";
cat.age = 12;
cat.sex = '母';
System.out.println(cat.name);//
System.out.println(cat.age);//
System.out.println(cat.sex);//
}
}