1.1 类与对象案例:
下面展示一些 内联代码片。
package com.itheima_02;
public class Student {
//成员变量
//姓名
String name;
//年龄
int age;
//成员方法
//学习的方法
public void study() {
System.out.println("好好学习,天天向上");
}
//吃饭的方法
public void eat() {
System.out.println("学习饿了要吃饭");
}
}
1.2 案例代码
下面展示一些 内联代码片。
package com.itheima_02;
public class StudentTest {
public static void main(String[] args) {
//类名 对象名 = new 类名();
Student s = new Student();
//System.out.println("s:"+s);//com.itheima_02.Student@da6bf4
//使用成员变量
System.out.println("姓名:"+s.name);//null
System.out.println("年龄:"+s.age);//0
System.out.println("----------");
//给成员变量赋值
s.name = "林青霞";
s.age = 30;
//再次使用成员变量
System.out.println("姓名:"+s.name);//林青霞
System.out.println("年龄:"+s.age);//30
System.out.println("----------");
//调用成员方法
s.study();
s.eat();
}
}
2.2 两个对象的内存图(共用方法区)
下面展示一些 内联代码片。
package com.itheima_03;
public class PhoneDemo2 {
public static void main(String[] args) {
Phone p = new Phone();
p.brand = "小米5s";
p.price = 1999;
p.color = "银色";
System.out.println(p.brand+"---"+p.price+"---"+p.color);
p.call("林青霞");
p.sendMessage();
Phone p2 = new Phone();
p2.brand = "IPhone7S";
p2.price = 7999;
p2.color = "土豪金";
System.out.println(p2.brand+"---"+p2.price+"---"+p2.color);
p2.call("张曼玉");
p2.sendMessage();
}
}
2.4 成员变量和局部变量区别
下面展示一些 内联代码片。
package com.itheima;
public class VariableDemo {
int x;
public void show() {
int y = 10;
System.out.println(x);
System.out.println(y);
}
}
private关键字的概述和特点
下面展示一些 内联代码片。
package com.itheima_01;
public class Student {
String name;
//int age;
private int age;
public void setAge(int a) {
if(a<0 || a>200) {
System.out.println("你给的年龄有误");
}else {
age = a;
}
}
public int getAge() {
return age;
}
public void show() {
System.out.println(name+"***"+age);
}
}
package com.itheima_01;
public class StudentTest {
public static void main(String[] args) {
//创建对象
Student s = new Student();
s.show();
//给成员变量赋值
s.name = "林青霞";
//s.age = 30;
//s.age = -30;
//通过方法赋值
s.setAge(-30);
s.show();
}
}



