注:函数和方法是同样东西。【因为我以前学习的时候有些书籍不是一样的说法,书看多了,我就习惯了不一样状况下用不一样的说法】java
首发时间:2018-03-22安全
class Dog{ String name; int foot=4; Dog(){//这是一个构造函数 this.name="旺财"; } void hello() { System.out.println("hello,this is a dog"); } static void static_hello() { System.out.println("hello,this is a dog too"); } } public class Demo { public static void main(String args[]) { Dog d=new Dog(); System.out.println(d.foot);//4 d.hello();//hello,this is a dog d.static_hello();//hello,this is a dog too Dog.static_hello();//hello,this is a dog too } }
根据变量、方法是否有static修饰能够分为实例变量,实例方法和静态变量(类变量),静态方法(类方法)函数
被static修饰的成员的特色:学习
随着类的加载而加载,优先于对象存在,静态成员内存位于方法区this
被全部对象所用享【因此可称为类变量或类方法】spa
能够直接类名调用3d
静态方法只能访问静态成员code
静态方法中不能够写this,super关键字对象
实例变量\方法跟静态变量\方法的区别比如:“泰迪狗类”好比有一个共有属性“狗种类名”,那么这个属性应该是全部泰迪狗都有的,而且是泰迪狗共享的,若是某一天人类想改泰迪狗的种类名称,那么应该是全部泰迪狗都改的(静态的);而每一只泰迪狗都有本身的主人,这是由每一只狗自身决定的,因此这是特有属性,即便这只狗换了主人,也不会影响别的狗。(实例的)blog
class Dog{ String name; Dog(){ this.name="旺财"; } Dog(String name){ this.name=name; } } public class Init_usage { public static void main(String args[]) { Dog d3=new Dog(); Dog d4=new Dog("小菜"); System.out.println(d3.name); System.out.println(d4.name); } }
class Man{ private int money; String name; Man(String name,int money){ this.name=name; this.money=money; } int getmoney(){ return money; } void setMoney(int money){ this.money=money; } } public class Private_usage { public static void main(String[] args) { Man m=new Man("lilei",2000); System.out.println(m.name);//lilei // System.out.println(m.money);//报错的,由于私有了,不能访问 // System.out.println(m.wife);//报错的,由于私有了,不能访问 System.out.println(m.getmoney()); //2000 m.setMoney(6000); System.out.println(m.getmoney());//6000 } }
类中的成员变量默认是带有this前缀的,但遇到同名时必须加以区分。
this加上参数列表(this(参数))的方式就是访问本类中符合该参数的构造函数
用于调用构造函数的this语句必须放在第一行,由于初始化动做要优先执行
class Person{ String name; int age; Person(String name,int age){ this.name=name; this.age=age; } void hello() { this.sysprint(); // sysprint(); } void sysprint() { System.out.println("hello world!"); } } public class This_usage { public static void main(String args[]) { Person p1=new Person("lilei",18); p1.hello();//hello world! } }