java.lang.*自动将引入
java.util.*工具包
java.net.*网络包
包的引入
import java.util.*
public class JavaHello
{
//this region will be run only once
static int i = 1;
static
{
i++;
}
//till here
public JavaHello()
{
i++;
System.out.println("i="+i);
}
public static void main(String[] args)
{
System.out.println("Hello World");
JavaHello jh1 = new JavaHello();
JavaHello jh2 = new JavaHello();
}
}
class Student
{
int age;
String name;
int fee;
static int totalFee;
public Student(int age, String name, int fee)
{
this.age = age;
this.name = name;
totalFee += fee;
}
//if static is free
//every class member will create a getTotalFee
//memory wasted
//类变量用类方法去访问与操作
//用Student.getTotalFee
//而不是student1.getTotalFee
//静态方法只能访问静态变量
//非静态方法可以访问静态变量
/*
public static int getTotalFee()
{
age++;//这是错的
return totalFee;
}
*/
{
return totalFee;
}
}
成员变量
成员方法——也就是函数
一个java只能有一个public类
1、抽象
2、封装
尽量把变量,函数写为私有,对程序进行保护
访问控制修饰符
class Clerk{
public String name;
private int age;
private float salary;
public Clerk(String name, int age, float salary){
this.name = name;
this.age = age;
this.salary = salary;
}
public float getSalary(){
return this.salary;
}
}
3、继承
代码复用
class Pupil extends student
{
}
class Kid extends Pupil//多重继承
{
}
方法的重载与覆盖
重载
1、方法名相同
2、方法的参数类型、个数、顺序至少有一个不同
3、方法的返回值可以不同
4、方法的修饰符可以不一样(public private protected)
但是只有修饰符不同是不可以构成重载
class GetMax
{
public int getMaxFunc(int a, int b)
{
return a;
}
public float getMaxFunc(float a, float b)
{
return a;
}
}
覆盖override
1、子类和父类的某个方法名称、返回类型、参数完全一致
2、子类方法不能缩小父类方法的访问权限
class Animal{
public void cry()
{
System.out.println("cry");
}
}
class Cat extends Animal{
public void cry
{
System.out.println("miaow");
}
}
4、多态
包:
作用
1、区分相同名字的类
2、控制访问范围
3、程序庞大时,方便管理
命令
package com.xx;
命名规范
com.xxx.xxx