// demonstrates static/non-static fields and methods// simulates a person (not in the Blade Runner sense)public class Person {// instance variable: age of this personprivate int age;// another instance variable: name of this personprivate String name;// static variable (shared by all instances): global populationprivate static int population = 0;// constructorpublic Person(int a, String n) {// copy arguments of constructor to instance variablesage = a;name = n;// increase the static counterpopulation++;}// static method (not per-instance)public static void printPop() {System.out.println(population);}// instance methodpublic void printName() {System.out.println(name);}// another instance methodpublic void printInfo() {System.out.println(age);// calling an instance method without a period// (uses same instance as what printInfo was called on)printName();}public static void main(String[] args) {// calling a static method using class name and period// what is the output?Person.printPop();// how many instances does this construct?Person myDad = new Person(33, "Lucius");Person myMom = new Person(44, "Pandora");Person myDentist = myMom;// calling an instance method using instance name and periodmyDentist.printInfo();// calling a static method without a period// (uses Person, the containing class, by default)// what is the output?printPop();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。