一、四种成员方法
1.无参无返回值方法
2.无参有返回式方法
3.有参无返回值方法
4.有参有返回值方法
在java中如何定义一个标准类 1.0版本
1、成员变量都要使用private关键字修饰
2、针对每一个私有的成员变量都要提供对应的setXxx()/getXxx()方法
private关键字:主要作用是体现封装的思想,被private修饰的成员无法在其他类中直接获取
private可以修饰成员变量,成员方法,构造方法
例子:求长方形的周长和面积
class ceshi {
private int length;
private int width;
public ceshi() {
}
public ceshi(int length, int width){
this.length = length;
this.width = width;
}
public void setLength(int length) {
this.length = length;
}
public int getLength() {
return length;
}
public void setWidth(int width) {
this.width =width;
}
public int getWidth() {
return width;
}
public int zhouchang(){
return (length+width)*2;
}
public int mianji(){
return length*width;
}
public void show(){
System.out.println("周长为"+zhouchang());
System.out.println("面积为"+mianji());
}
}
public class ceshidemo{
public static void main(String[] args) {
ceshi cs=new ceshi();
cs.setLength(12);
cs.setWidth(13);
cs.show();
}
}
二、静态方法
java中提供了一个关键字,可以将变量变成类变量(共享变量),这个关键字:static,被static修饰的成员,会被该类所有的对象共享。
class Person {
private String name;
private int age;
private static String nationality;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, String nationality) {
this.name = name;
this.age = age;
this.nationality = nationality;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public void show() {
System.out.println("姓名:" + name + ", 年龄:" + age + ", 国籍:" + nationality);
}
}
public class StaticDemo1 {
public static void main(String[] args) {
//创建几个对象,都是大将
Person p1 = new Person("赵云", 18, "中国");
Person p2 = new Person("关羽", 17);
Person p3 = new Person("马超", 19);
p1.show();
p2.show();
p3.show();
}
}
注意事项:
1.被static修饰的成员叫做类成员,被该类所有的对象共享。
2.被static修饰的成员优先对象而存在于方法区中的静态区,并且有个默认值。
3.被static修饰的成员叫做类成员,将来可以直接使用类名来访问:类名.类成员
三、构造方法
1.可以用作创建对象。
2.可以在创建对象的同时给该对象的成员变量进行赋值。