解释类和实例之间的区别
Explain the difference between class and instance:class 是一个类,Object是对象。
类(class)是一个集体的描述,对象(Object)是这个集体里面的一个个体的描述。
例如:人就是一个类,你,我,他就是对象。
星球是一个类,地球是对象。
猫科动物是一个类,老虎是对象。
Two aspects make up a class/object: 1. State (attributes) 2. Behaviour (functions/methods)
类和对象由两部分组成:状态和行为。
Example – Bank Class State: name, location, list of accounts/employees Behaviour: create an account, close account, pay interest
Example – Bank Account Class State: owner, balance, fees Behaviour: deposit, withdraw
class命名规则:Classes: nouns, the first letter of each word capitalized
Now that we have created a class, we can create instances of that class
创造类有三个步骤:Three steps: 1. Declaration 2. Instantiation 3. Initializatio n
Constructor is used to initialize an object whereas method is used to exhibits functionality of an object.
方法:
参数:原料
返回值:方法中得出的数据
定义方法的完整格式
修饰符 返回值类型 方法名称 (参数类型 参数名称。。){
方法体
return 返回值
}
return:两个作用:1.停止当前方法2.将后面的结果数据返回值还给调用处
方法三要素:
1.返回值类型
2.方法名称
3.参数列表
public class demo{
public static void main (String[] args) {
//单独调用
sum(10,20) ;
//打印调用
System.out.println(sum(10,20);
//赋值调用
int number = sum(15,25);
System.out.println( " 变量的值" + number);
}
public static int sum(int a, int b){
int result = a + b;
return result;
}
方法的有参和无参:
有返回值跟无返回值:
方法重载
方法名一样
了解构造函数的作用
实现方法以指定类行为
定义方法重载
廖雪峰教程:
继承
超类super class
父类parent class
子类base class
Java只允许一个class继承自一个类,因此,一个类有且仅有一个父类。只有Object
特殊,它没有父类。
protected
继承有个特点,就是子类无法访问父类的private
字段或者private
方法。例如,Student
类就无法访问Person
类的name
和age
字段
class Person {
private String name;
private int age;
}
class Student extends Person {
public String hello() {
return "Hello, " + name; // 编译错误:无法访问name字段
}
}
为了让子类可以访问父类的字段,我们需要把private
改为protected
。用protected
修饰的字段可以被子类访问
class Person {
protected String name;
protected int age;
}
class Student extends Person {
public String hello() {
return "Hello, " + name; // OK!
}
}