类与对象
java的类class可以想象为一个对象,它的命名一般为首字母大写,在这个对象里可以定义它的属性和方法(我认为这里的方法和c语言的函数很像),方法就是这个对象能干什么。例如:人是一个对象,都有名字、年龄、性别的属性,都会吃饭,就可以写为下面的代码:
package javalearn;
class Person{
String name;
int age;
char sex;
public static void power(){
System.out.print("我会吃饭");
}
}
public class Learn {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person onepeople = new Person();
onepeople.name = "onepeople的名字是李斯";
System.out.println(onepeople.name);
onepeople.power();
}
}
这段代码会输出:onepeople的名字是李斯 我会吃饭
方法的递归调用就和c语言的函数递归调用很像,不多说。
封装性:利用private
private int age;不是本对象将不能改变本对象的age属性,要利用个体get()与set()函数,具体用法:
package javalearn;
class Person{
private int age;//设置了私有属性,其他对象不能修改
public int getAge() {//通过get方法得到,注意主类的调用方法
return age;
}
public void setAge(int age) {//通过set方法设置,注意主类的调用方法
this.age = age;
}
}
public class Learn {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person onepeople = new Person();
onepeople.setAge(30);
System.out.println(onepeople.getAge());
}
}
构造方法:
构造方法名称与类名一致,无返回值,主要用于对象属性的初始化,可以重载(其中有一个调用无参数构造方法的知识点)。使用方法
package javalearn;
class Person{
int age;
public Person(int age) {//记得名称要一样
this.age=age;
System.out.print(this.age);
}
}
public class Learn {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person onepeople = new Person(30);
}
}