Java基础

查看对象在内存中的布局

import import org.openjdk.jol.info.ClassLayout;
System.out.println(ClassLayout.parseInstance(student).toPrintable());

注释

单行:Ctrl + /

多行:Ctrl + shift + / 常用于:说明方法作用或一段代码功能

文档:/** 常用于:类定义或公有方法定义的前面

创建数组类

ArrayList<Integer>arraylist=new ArrayList();

常量关键字:final

算数左移(符号位不变,右边补零p<<3)

算数右移(符号位不变,左边补符号位p>>3)

逻辑右移(左边补0 p>>>3)

三目运算符

q>r?a:b

instance判断是否是Student类的实例

if(s1 instanceof student)
{
System.out.pritln("s1是student的实例");
}

类型转换

boolean类型的不能转换成其他类型

在混合运算中,容量小的类型自动转换为大容量的数据类型,排序如下:

byte,short,char->int->long->float->double

byte,short,char之间不会相互转换,他们三者在计算时首先会转换为int类型

容量大的数据类型转换为容量小的类型时要加上强制转换符

有多种类型的数据混合运算时,系统首先自动将所有的数据转换成容量最大的那种数据类型,然后进行计算

默认出现小数都算double

默认出现数字都算int

public class Main {
public static void main(String[] args)
{
int i1=123;
int i2=456;
double d1=(i1+i2)*1.2;//自动类型转换
float f1=(float)((i1+i2)*1.2);
byte b1=67;
byte b2=89;
byte b3=(byte)(b1+b2);
double d2=1e200;
System.out.println(d2);
float f2=(float)(d2);
System.out.println(f2);//打印输出 f2 的值。由于 d2 超出了 float 的表示范围,所以 f2 将会是特定的值,通常是 Infinity 或 -Infinity,这取决于 d2 的正负。
float f3=1.23f;
long l1=123;
long l2=3000000L;
float f4=l1+l2+f3;
System.out.println(f4);
long l3=(long)f4;
System.out.println(l3);
byte a=(byte)128;
System.out.println(a);
}
}

for循环遍历数组

int arr[]={1,2,3,4,5}
for (int i:arr)
{
System.out.println(i);
}

类的定义格式(移动窗口例子)

public class Main {
public static void main(String[] args)
{
MyFrame myFrame=new MyFrame();
myFrame.createWindow();
myFrame.walk();
}
}
import java.awt.*;
public class MyFrame
{
private int selfWidth=500,selfHeigth=300;
private int x=200,y=300;
private int screenWidth=0,screenHeigth=0;
private int ScreenWidth=0,ScreenHeight=0;
private int loopCount=0;
private boolean flagX=true,flagY=true;
private Frame frame;
public void createWindow()
{
//创建窗口
frame=new Frame("台球窗口例子");
//窗口的可见性
frame.setVisible(true);
//窗口的大小
frame.setSize(selfWidth,selfHeigth);
//窗口的背景色
frame.setBackground(new Color(10,10,200));
//窗口位置
frame.setLocation(x,y);
//窗口的大小是否可改变
frame.setResizable(true);
//获取屏幕尺寸
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
screenWidth=screenSize.width;
screenHeigth= screenSize.height;
}
public void walk()
{
while (true)
{
loopCount+=1;
try {
Thread.sleep(4);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if(x<0||(x+selfWidth)>screenWidth)
{
flagX=!flagX;
}
if(y<0||(y+selfHeigth)>screenHeigth)
{
flagY=!flagY;
}
if(flagX)
{
x+=1;
}
else
{
x-=1;
}
if(flagY)
{
y+=1;
}
else
{
y-=1;
}
frame.setLocation(x,y);
}
}
}

继承的基本概念

访问父类用super.

访问权限控制

private:只能在类内部访问(权限要求最高,能被访问的范围越小)。

default(啥也不写,默认的):包级权限,可以被同包的其他类访问

protected:可以被子类访问,也可以被同包的其他类访问到, protected在被同包的类访问的基础上,还能被其他包的子类访 问。

public:可以在类外部访问(权限要求最低)