JAVA学习笔记(6)
一、类与对象
1.类和对象的概念
设计:name,age,high,weight…
class People{ }
类
class People{
//1.属性:字段,成员变量,实例变量
String name;
int age;
//2.行为:函数,成员方法,实例方法
void eat(){}
}
eg:
class Airplane{
String color;
int weight;
String address;
void fly(){
}
void down(){
}
}
实例化阶段:
People p = new People();
对象大小:对象头(8个字节)+成员变量+内存填充
(对象大小总体是8的倍数)
class People{ }
People p = new People();
class People{
int age;
int id;
void eat(){}
}
垃圾回收器->垃圾回收机制
“垃圾”:标记-清扫 引用计数int count
如果当前这个对象没有引用变量所引用的话即就是引用变量count = 0;
2.成员变量的初始化方式
People p = new People(); //"()":初始化
成员变量访问
eg:
public class TestDemo3 {
public static void main(String[] args) {
People p1 = new People("lisi");
//new:
// 1.堆上开内存
//2.调用构造方法初始化实例变量
//成员变量的访问,成员访问
p1.eat();
System.out.println(p1.name);
People p2 = new People("zs");
p2.eat();
System.out.println(p2.name);
}
}
public class People {
public String name;
private int age;
//构造方法:
People(String name){//如果自己写构造,JVM不再提供默认无参构造
this.name = name;//就近原则
age = 10;
}
public String getName(){
return name;
}
public void eat(){//eat(p1) this
System.out.println(this.name+"吃饭");
}
}
3.this关键字:如果存在命名冲突,一定加上this.;
4.访问限定符:public 公有 private 私有 默认:包访问权限:同包路径可以访问
eg:
图书:
属性:书名 出版社 价格
行为:isRead(){} isBorrowed()
创建两本书;
查看当前书籍信息,有没有被借走
book1.isBorrowed();/借书成功/
book1.isBorrowed();/借书失败/
public class Book {
private String name;
private int price;
private String publish;
private String author;
private boolean read = false;
public Book(String name, int price, String publish, String author) {
this.name = name;
this.price = price;
this.publish = publish;
this.author = author;
}
public boolean isRead(){
return this.read;
}
public void read(){
this.read = true;
}
public String getName() {
return name;
}
}
public class TestDemo {
public static void main(String[] args) {
Book book = new Book("水浒传",100,"北京出版社","施耐庵");
book.read();
boolean flag = book.isRead();
System.out.println(flag);
}
}