规则:方法名一致,参数不一致,与返回值无关
package com.zhongxin.method;
public class Student {
public void add(int a, int b) {
System.out.println(a + b);
}
public void add(int a) {
System.out.println(a);
}
public void add(int a, double b) {
System.out.println(a + b);
}
public void add(double a, double b) {
System.out.println(a + b);
}
}
package com.zhongxin.method;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.add(4, 3);
s.add(4);
s.add(4,3.0);
s.add(4.0, 3.0);
}
}
java内存包含了:
通过函数的形式将一些代码细节包装起来,防止外部代码的随机访问。
要访问这些数据就必须通过调用函数来完成。
好处:
package com.zhongxin.method;
public class Phone {
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
if (size < 1 || size > 10) {
System.out.println("size设置失败");
} else {
this.size = size;
}
}
}
package com.zhongxin.method;
public class Test2 {
public static void main(String[] args) {
Phone p = new Phone();
p.setSize(-2);
int size = p.getSize();
System.out.println(size);
}
}
两个类之间通过extends
关键字来描述父子关系,子类可以拥有父类的公共方法和公共属性。
语法:
public class 父类{
}
public class 子类 extends 父类{
}
父类Phone
package com.zhongxin.extend;
public class Phone {
private int size;
private String brand;
public String color;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void call(){
System.out.println("打电话");
}
public void show() {
System.out.println("show...");
}
}
子类Phone4S
package com.zhongxin.extend;
public class Phone4S extends Phone {
public void siri() {
System.out.println("你好");
}
}
使用
package com.zhongxin.extend;
public class Test {
public static void main(String[] args) {
Phone p = new Phone();
Phone4S p4 = new Phone4S();
p.call();
p4.call();
p4.siri();
}
}
Object
super
指向父类
super()
调用父类构造方法
this
指向当前类(子类)
this()
调用本类其他构造
前提条件:
子父类中出现一摸一样的方法
作用:
公共的
受保护的,必须继承后才能访问
本类或者同一个包pakage
下可以访问
私有的,只有本类可以访问
上面1~4 权限依次降低
静态
常量
public final int b = 10;
final
抽象