格式说明
类
public static void main(String[] args) {
// class 是程序的基础组成部分 不同的class拥有不同的功能
// Scanner 类允许我们通过控制台向程序内进行输入一些数据
// java提供上万个类 , 有一些统一的使用格式
// 创建类的对象
// 类名 对象名 = new 构造函数;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一段文字:");
String string = scanner.nextLine();
System.out.println(string);
scanner.close();
}
方法
public class Demo3 {
public static void main(String[] args) {
// 把重复使用的代码写成方法
// 方法声明的时候有参数,调用的时候必须为每一个参数赋一个值,
// 参数类型和顺序也要保持一致
method3("大米");
method3("小米");
method3("绿豆");
method4("大米", 30);
plus(1, 2);
// 定义一个和返回类型相同的变量来接收数据
System.out.println(method5(13.7, 0.6));
}
private static void method3(String name) {
// 参数可以当做一个普通的变量来使用
System.out.println("制作:" + name + "粥!");
}
// 在方法中声明的参数叫做形参 传递的叫做实参
private static void method4(String name, int minute) {
// 参数可以当做一个普通的变量来使用
System.out.println("制作:" + name + "粥!定时" + minute + "分钟!");
}
private static int plus(int x, int y) {
return x + y;
}
// 方法传递给外部的一个数据,供后续的其他步骤使用
public static double method5(double a,double b) {
return a+b;
}
// 1.消除重复的代码就是封装成方法
// 2.把大段的代码拆分成小的方法,由几个调用组成完整的功能
}
构造方法
public class People {
// 属性
public String name;
public int age;
public boolean sex;
// 构造方法一般用于初始化类,可重载
// 修饰符只能是public 且无返回值
public People() {
System.out.println("我是people的无参构造方法");
}
public People(String name,int age,boolean sex){
this.name = name;
this.age = age;
this.sex = sex;
System.out.println("我是people的有参构造方法");
}
}
this和super的区别以及方法重写
先创建一个Bird类
public class Bird {
public String name = "鸟";
public void fly(){
System.out.println("渣渣渣~~~~");
}
}
再创建一个企鹅,鸵鸟类
public class Ostrich extends Bird{
public void fly() {
System.out.println("跑跑跑~~~");
}
}
public class Penguin extends Bird{
// 属性也可以被重写
public String name = "企鹅";
@Override // 注解 看做一个特殊的标志
public void fly(){
System.out.println("我是企鹅扭扭扭扭~~~~");
// this调用父类的属性和方法
// super调用父类的属性和方法
// super 和 this 的作用差不多
// super.fly();
}
public void thisMethod(){
System.out.println("我是this调用的!");
System.out.println(this.name);
this.fly();
System.out.println("==============");
}
public void supermethod(){
System.out.println("我是super调用的!");
System.out.println(super.name);
super.fly();
System.out.println("==============");
}
// 方法的重载 和 重写
// 重载 : 多个方法 方法名相同 ,参数不同 在一个类中
// 重写 : 子类方法和父类方法完全相同 但实现的功能不同
}
创建Mainclass来进行测试
public class MainClass {
public static void main(String[] args) {
// 鸵鸟继承自bird,自动拥有了bird中的方法fly()
// 子类可以重写继承父类的方法,重新实现,只会影响当前这个子类
Ostrich ostrich = new Ostrich();
ostrich.fly();
Bird bird = new Bird();
// 对父类和其他子类没有影响
bird.fly();
Penguin penguin = new Penguin();
penguin.fly();
penguin.thisMethod();
penguin.supermethod();
}
}