toString() 方法
- 在java中,所有对象都有to_String()这个方法
- 创建类时没有定义toString方法输出对象时会输出对象的哈希码值(内存地址)
- 它通常只是为了方便输出,比如System.out.println(xx),括号里的xx如果不是String类型的话,就自动调用xx的toString方法
- 是sun公司开发java时为了方便所有类的字符串操作而特意加入的一个方法
class Whale{
String name;
int age;
public String toString(){
return "它的名字:"+name+" 它的年龄:"+age;
}
}
public class test5_tostring {
public static void main(String[] args){
//String name = new String("Hello");
Whale myfriend = new Whale();
myfriend.name = "鲸·小虎";
myfriend.age = 9;
System.out.println(myfriend); //没有定义toString时,输出Whale@6b97fd
}
}
this关键字
- 在类的方法定义中,成员变量和参数重名时,如果需要使用成员变量就必须使用this
class Whale1{
String name;
int age;
String sex;
public void set(String name, int age, String sex){
this.name = name; //当参数与属性名一样时,必须使用this关键字
this.age = age; //将参数赋值给属性
this.sex = sex;
}
public String toString(){
return "名字:"+name+" 年龄:"+age+" 性别:"+sex;
}
}
public class test_this {
public static void main(String[] args){
Whale1 myWhale1 = new Whale1();
myWhale1.set("小虎鲸", 5, "男");
System.out.println(myWhale1);
}
}
封装
面向对象三大基本特征之一:
- 封装(encapsulation):就是把不想或者不告诉别人的东西隐藏起来,把可以告诉别人的公开。
- 做法:修改属性的访问权限来限制对属性的访问。并为每一个属性创建一对取值方法和赋值方法,用于对这些属性的访问。
class Student{
String name;
int age;
private char gender; //设置访问权限,只能内部引用
//设置属性
public void setGender(char gender){
if (gender=='男'||gender=='女'){ //char类型的要用单引号,不然会报错
this.gender = gender; //参数名和属性名一样,采用了this关键字
}else{
System.out.println("请输入正确的性别:");
}
}
//获取属性
public char getGender(){
return this.gender; //这里用不用this都可以
}
}
public class test7 {
public static void main(String[] args){
Student one = new Student();
one.setGender('男');
System.out.println(one.getGender());
}
}
方法的重载
- 方法的重载是指一个类中可以定义有相同的名字,但参数不同的多个方法,调用时会根据不同的参数列表选择应的方法。
class Score2{
public void max(int a, int b){
System.out.println(a>b?a:b); //三元运算符,a大于b吗,如果大于则a,否则b
}
public void max(double a, double b){ //三个方法的名字都一样,参数不一样
System.out.println(a>b?a:b);
}
public void max(int a, int b, int c){
int t = a>b?a:b;
System.out.println(t>c?t:c);
}
}
public class test8_max {
public static void main(String[] args){
Score2 onePeople = new Score2();
onePeople.max(99, 8, 921);
}
}
构造方法(构造函数)
- 使用new+构造方法 创建一个新的对象
- 构造方法是定义在java类中的 一个用来初始化对象的函数
- 构造方法与类同名且没有返回值
class Cat{
private String name;
private int age;
/*无参数的构造方法
* Cat(){
}*/
//有参无返回的构造函数
Cat(String name, int age){
this.name = name;
this.age = age;
System.out.println(this.name+" "+this.age);
}
//普通函数
void get(){
System.out.println("这是一个普通方法");
}
}
public class test9 {
public static void main(String[] args){
//Cat one = new Cat(); 简单的构造方法
Cat one = new Cat("鲸小虎",12);
one.get();
}
}
class Cat{
private String name;
private int age;
//无参数的构造方法
Cat(){
}
//有参无返回的构造函数
Cat(String name, int age){
this.name = name;
this.age = age;
}
//普通函数
void get(){
System.out.println(this.name);
}
}
public class test9 {
public static void main(String[] args){
Cat one = new Cat(); //简单的构造方法
Cat two = new Cat("鲸小虎",12);
//当没有设置构造函数时,该条语句会报错,
//应该使用上一条,因为系统会默认有简单的构造函数
one.get(); //null
two.get(); //鲸小虎
}
}