发表于: 2017-11-05 21:21:57

1 862


今天完成的任务:

1.了解了静态变量,静态方法,静态代码块:

在变量里面加static,就是静态变量。在一个类里面创建了静态变量,那么变量就变成了类级别的,所有对象共享。并且调用的时候不需要创建对象,直接用类就可以调用。方法加static也是一样的,可以用类直接调用,不需要创建对象。静态变量(方法)的只能访问或者调用静态方法(变量),实例方法(变量)的能访问或者调用静态变量(方法),因为静态的是在构造对象开辟内存之前运行的。

先创建一个构造类

public class Gouzao {
public void m(Yuan yuan){yuan.setR(45);}
   {
System.out.println("构造代码块1");
}
Gouzao(){
System.out.println("构造器1");
}
{
System.out.println("构造代码块2");
}
static {
System.out.println("静态代码块");
}

}

然后再创建一个普通类调用构造类:

public class demo {
   public static void main(String[] args) {
{System.out.println("普通代码块");}
{System.out.println("普通代码块");}
Gouzao g=new Gouzao();
Gouzao g1=new Gouzao();
}
}

运行demo,运行结果如下:

普通代码块
普通代码块
静态代码块
构造代码块1
构造代码块2
构造器1
构造代码块1
构造代码块2
构造器1

这说明构造代码块运行优先于构造器,有多少对象运行多少次。静态代码块优先于构造代码块,她是随着类的加载运行的,加载好之后调用多少方法跟静态代码块没关系了。

2.了解了public和private的区别:

public是公开的,一个文件里面只能有一个public class,但是可以有两个类。  public class里面可以有内部类。

private用法:在变量或方法前加private那么方法或变量就不能全局调用,只能在这个类里面调用,如果想调用,可以在变量里generate然后getter and setter,就可以再外面调用了。

3.关键字this:

定义完数据域和方法之后可以generate然后constructor生成构造器,构造器里的this是为了区分成员变量和参数。类里成员变量默认加this。如下所示:

首先创建数据域。数据为了能调用,于是generate然后getter and setter。就然后创建方法,再generate然后constructor生成构造器

public class Yuan{
Yuan(){c++;}

public Yuan(double r, int a) {
this.r = r;
this.a = a;
}

public double getR() {
return r;
}

public void setR(double r) {
this.r = r;
}

public int getA() {
return a;
}

public void setA(int a) {
this.a = a;
}

public static int getC() {
return c;
}

public static void setC(int c) {
Yuan.c = c;
}

public static double getPI() {
return PI;
}

private double r;//数据域,一般用private封装
  private int a;
private static int c;//static关键字 将变量变为类级别的 所有对象共享
  final  static double PI=3.141592653597932;//常量名称全部大写 不同的单词下划线隔开
  double mianji(){
return r*r*Math.PI;
}
static int a(){return 0;}//方法前加static可用类直接点出方法。不需要创建对象
}

在外部主函数调用:

public class DiaoYong{
public static void main(String[] args) {
       System.out.println(Yuan.PI);
}
}

遇到的问题:

设置类:

public class Yuan{
Yuan(){c++;
public  Yuan(double r, int a) {
this.r = r;
this.a = a;
}

public double getR() {
return r;
}

public void setR(double r) {
this.r = r;
}

public int getA() {
return a;
}

public void setA(int a) {
this.a = a;
}

public static int getC() {
return c;
}

public static void setC(int c) {
Yuan.c = c;
}

public static double getPI() {
return PI;
}

private double r;
private int a;
private static int c;
  double mianji(){
return r*r*Math.PI;
}
static int a(){return 0;}
}

调用类:

public class DiaoYong{
public static void main(String[] args) {

Yuan y=new Yuan(9,9);
Yuan y0=new Yuan();
Yuan y1=new Yuan();
System.out.println(Yuan.getC());
}
}

运行结果:2

public class DiaoYong{
public static void main(String[] args) {

Yuan y=new Yuan();
Yuan y0=new Yuan();
Yuan y1=new Yuan();
System.out.println(Yuan.getC());
}
}

运行结果:3

变量c不是应该调用一次类就增加1吗,为什么在输入数据之后就不增加了呢?

明天的任务:java基础继续补,越补基础越理解做任务过程中不懂得地方。争取两天内补完java基础。


返回列表 返回列表
评论

    分享到