面向对象
三大特征:封装、继承、多态
方法: main也是个方法
//方法
public static void main(String[] args) {
Demo01 demo01 = new Demo01();
demo01.sayHello();
}
public String sayHello(){
return "hello";
}
public void readFile(String file) throws IOException{
}
static修饰的方法,随着类的加载而加载,不需要通过类的实例对象调用
// static 和类一起加载
public static void a(){}
public void b(){}
public static void main(String[] args) {
//实际参数和形式参数的类型要相同
int add = add(2, 3);
System.out.println(add);
}
public static int add(int a,int b){
return a+b;
}
Java 是值传递的
public static void main(String[] args) {
//Java是 值传递
int a = 1;
System.out.println(a); // 1
change(a);
System.out.println(a);// 1
}
public static void change(int a){
a = 10;
}
引用传递:对象,本质还是值传递
public static void main(String[] args) {
//引用传递:对象,本质还是值传递
Person person = new Person();
System.out.println(person.name); //jie
change(person);
System.out.println(person.name); //啊杰
}
public static void change(Person person){
person.name = "啊杰";
}
}
class Person{
String name = "jie";
}
构造器:构造器:
1.和类名相同
2.没有返回值
作用:
1.new 本质是调用构造器
2.初始化对象的值
注意点:
1.定义有参构造之后,如果还想使用无参构造器,要显示的定义一个
this表示当前类
public class Person {
String name;
//1.使用new关键字,本质是再调用构造器
//2.用来初始化值
public Person(){
}
public Person(String name){
this.name = name;
}
}
public String name;
public int age;
public void shout(){
System.out.println(this.name+"叫");
}
public static void main(String[] args) {
Pet dog = new Pet();
dog.name = "旺财";
dog.age = 3;
dog.shout();
}
/*
1.类与对象:
类是一个模板:抽象的,对象是一个具体的实例
2. 方法
定义、调用
3.对应的引用
引用类型: 基本类型(8)
对象是通过引用来操作的: 栈 --> 堆
4. 属性: 字段Field 成员变量
默认初始化:
数字: 0 0.0
char: u0000
boolean: false
引用:null
5.对象的创建和使用
-必须使用new关键字创建对象,构造器调用
- 对象的属性:jie.name
- 对象的方法:jie.sleep()
6.类
静态的属性 --> 属性
动态的行为 --> 方法
三大特征
封装、继承、多态
*/
封装性:
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统可维护性增加了
public class Student extends Person{
private String name;
private int id;
private char sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
继承性
public class B {
public void test(){
System.out.println("B ==>test()");
}
}
类A继承了类B,还重写了父类中的test方法
public class A extends B{
@Override
public void test(){
System.out.println("A ==>test()");
}
}
多态:
1.父类的引用指向子类的对象
2.把子类转为父类,向上转型
3.把父类转为子类,向下转型,需要强制转换
4.方便方法的调用,减少重复的代码,简洁
public static void main(String[] args) {
A a = new A();
B b = new A();
a.test();
b.test();
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了:父类的引用指向子类的对象
Student s1 = new Student();
Person s2 = new Student();
//对象能执行哪些方法,主要看左边的类型,和右边的关系不大
s1.eat();
s1.run();
// s2.eat();//子类重写了父类的方法,执行子类的方法
s2.run();
System.out.println(s1 instanceof Person);
}
多态注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类,有联系,类型转换异常! ClassCastException
3.存在条件: 继承关系,方法需要重写,父类引用指向子类的对象