类的定义
类的定义步骤:
定义类
编写类的成员变量
编写类的成员方法
手机类:
类名:
手机(Phone)
成员变量:
品牌( brand)
价格(price)
成员方法:
打电话(call)
发短信( sendMNessage)
package com.ithema_01;
/*
类的定义
类的定义步骤:
定义类
编写类的成员变量
编写类的成员方法
手机类:
类名:
手机(Phone)
成员变量:
品牌( brand)
价格(price)
成员方法:
打电话(call)
发短信( sendMNessage)
*/
public class Phone {
//成员变量
String brand;
int price;
//成员方法
public void call(){
System.out.println("打电话");
}
public void sendMessage(){
System.out.println("发短信");
}
}
创建对象 格式:类名对象名= new类名(); 范例:Phone p = new Phone( ); 使用对象 1:使用成员变量 格式:对象名.变量名 范例:p.brand 2:使用成员方法 格式:对象名.方法名() 范例:p.caLL()
package com.ithema_01;
/*
创建对象
格式:类名对象名= new类名();
范例:Phone p = new Phone( );
使用对象
1:使用成员变量
格式:对象名.变量名
范例:p.brand
2:使用成员方法
格式:对象名.方法名()
范例:p.caLL()
*/
public class PhoneDemo {
public static void main(String[] args) {
//创建对象
Phone p=new Phone();
//使用成员变量
System.out.println(p.brand);
System.out.println(p.price);
p.brand="小米";
p.price=2999;
System.out.println(p.brand);
System.out.println(p.price);
//使用成员方法
p.call();
p.sendMessage();
}
}
案例:学生
package com.itheima_02;
/*
学生类
*/
public class Student {
//成员变量
String name;
int age;
//成员方法
public void study(){
System.out.println("好好学习,天天向上");
}
public void duHomework(){
System.out.println("键盘敲烂,月薪过万");
}
}
package com.itheima_02;
/*
学生测试类
*/
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s = new Student();
//使用对象
System.out.println(s.name + "," + s.age);
s.name="林青霞";
s.age=30;
System.out.println(s.name + "," + s.age);
s.study();
s.duHomework();
}
}
多个对象
package com.ithema_02;
public class StudentText02 {
public static void main(String[] args) {
//创建第一个对象并使用
Student s1=new Student();
s1.name="林青霞";
s1.age=30;
System.out.println(s1.name+","+s1.age);
s1.study();
s1.duHomework();
//创建第二个对象并使用
Student s2=new Student();
s2.name="张曼玉";
s2.age=28;
System.out.println(s2.name+","+s2.age);
s2.study();
s2.duHomework();
}
}
多个对象指向相同
package com.ithema_03;
/*
多个对象指向相同
*/
public class StudentText03 {
public static void main(String[] args) {
//创建第一个对象并使用
Student s1=new Student();
s1.name="林青霞";
s1.age=30;
System.out.println(s1.name+","+s1.age);
//把第一个对象的地址赋值给第二个对象
Student s2=s1;
s2.name="张曼玉";
s2.age=28;
System.out.println(s1.name+","+s1.age);
System.out.println(s2.name+","+s2.age);
}
}