关于java:Java的第二天

面向对象编程

1.成员办法:不须要返回值时应用void关键字,有时应用return关键字,作用是实现各种操作

public void showGoods(){
  System.out.println("hello world");
}

public int showGoods(){
  System.out.println("hello world");
  return 1;
}

2.构造方法:没有返回类型,不能用void,名称与本类雷同,实现成员的初始化

public class EggCake{
  int eggCount;
  public EggCake(int eggCount){
        this.eggCount = eggCount;···成员初始化
       }
}

当创立无参对象时,会默认调用无参的构造方法,创立y有参对象时,会默认调用有参的构造方法
Book book = new Book():···已调用无参的构造方法

Tip1:
当类中存在有参构造方法时,类不会为类主动生成一个无参的构造方法,只能本人创立,只有类中没有任何有参构造方法时,类才会本人生成一个无参的构造方法。

Tip2:
当一个类中没有任何有参的构造方法时,类会主动生成无参的构造方法

借阅书《飘》的两种实现形式

无有参构造方法:

public class BorrowABook{
       public BorrowABook(){
   }···此办法运行时类主动生成,不会显示
       public void borrow(String name){
       System.out.println("借阅"+name);
   }
       public static void main(String[] args){
       BorrowABook book = new BorrowABook();
       book.borrow("<<飘>>");
   }
}

存在有参构造方法:

public class BorrowABook{
       String name;
       public BorrowABook(String name){
       this.name = name;
   }
       public void borrow(){
       System.out.println("借阅"+name);
   }
       public static void main(String[] args){
       BorrowABook book = new BorrowABook("<<飘>>");
       book.borrow();
   }
}

3.局部变量和成员变量

public class EggCake{
  int eggCount;···成员变量
  public EggCake(int eggCount)···局部变量

4.this 关键字(当成员变量和局部变量雷同时应用)

this 示意成员变量:this.成员变量 应用构造方法:this(不填/参数) 应用成员办法:this.成员办法(不填/参数)

public class EggCake{
  int eggCount;
  public EggCake(int eggCount){
        this.eggCount = eggCount;···this代表int eggCount中的eggCount,相当于成员变量
       }
}
public class Zi{
     public int age =30;--- 成员变量的age
     public void show(){
        int age = 20;  --- 局部变量的age
        System.out.println(age);
        System.out.println(this.age);
        }

}
打印后果:
20
30

5.static
变量:共享的变量应用static润饰
办法:不想创立类的对象时但想应用的办法,应用static润饰
静态方法不能间接拜访非动态成员。

public class Pool{
    public static int water = 0;
    public static void inlet(){
      water = water +3;
      }
}

public static void main(String[] args){
    Pool pool1 = new Pool();···本应有这行代码,但因inlet()为静态方法,能够间接调用,所以只需上面一行代码
    Pool.inlet();
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理