本文目錄一覽:
java中怎麼創建對象數組
首先我們需要創建一個class:
class Student{
String name;
double score;
String num;
Student(String n,double s,String m){
name=n;
s=score;
num=m;
}
public static void printInfo(){
System.out.println(num+”,”+name+”,”+score);
}
}
接下來我們對此類進行數組的創建:
//1
Student stu[];span style=”white-space:pre” /span//聲明數組。
stu=new Student [3];span style=”white-space:pre” /span//創建數組,這裡是創建的一個引用的數組,每一個引用並沒有確切的地址。
for(int i=0;i3;i++){span style=”white-space:pre” /span//為數組創建對象,也就是說為創建的引用關聯到確切的地址。
stu[i]=new Student();
}
//2
Student stu[]=new Student [3];
for(int i=0;i3;i++){
stu[i]=new Student();
}
//3
Student stu[]=new Student{new Student(sjl,87,01),new Student(ljs,98,02),new Student(lls,92,03)};
java 對象數組定義是什麼?
對象是類的一個實例(對象不是找個女朋友),有狀態和行為。例如,一條狗是一個對象,它的狀態有:顏色、名字、品種;行為有:搖尾巴、叫、吃等。
數組的三種定義方法
1.數組類型[] 數組名=new 數組類型[數組長度];
2.數組類型[] 數組名={數組0,數組1,數組2,數組3,….};
3.數組類型[] 數組名=new 數組類型[]{數組0,數組1,數組2,…};
Java作為一種面向對象語言。支持以下基本概念:
多態、繼承、封裝、抽象、類、對象、實例、方法、重載
Java 是由Sun Microsystems公司於1995年5月推出的高級程序設計語言。 Java可運行於多個平台,如Windows, Mac OS,及其他多種UNIX版本的系統。
Java是一門面向對象編程語言,不僅吸收了C++語言的各種優點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特徵。Java語言作為靜態面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優雅的思維方式進行複雜的編程 。
Java具有簡單性、面向對象、分散式、健壯性、安全性、平台獨立與可移植性、多線程、動態性等特點 。Java可以編寫桌面應用程序、Web應用程序、分散式系統和嵌入式系統應用程序等
java定義對象數組
package com.panel.test;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CreatBall extends JPanel {
private static final long serialVersionUID = 1L;
public static Balls ball[] = new Balls[2]; // 此處要初始化數組,否則在構造方法里報空指針錯誤
int x, y, radius;
Color c;
public CreatBall() {
super();
ball[0] = new Balls(10, 10, 20, Color.black);
ball[1] = new Balls(40, 40, 20, Color.blue);
}
public static void main(String args[]) {
JFrame f = new JFrame(“ceshi”);
f.add(new CreatBall());
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
this.drawBall(x, y, radius, g, c);
}
public void drawBall(int x, int y, int radius, Graphics g, Color c) {
for (int i = 0; i = 1; i++) {
g.setColor(ball[i].getColor());
g.fillOval(ball[i].getX(), ball[i].getY(), ball[i].getRadius(),
ball[i].getRadius());
}
}
}
class Balls {
private int x, y, radius;
private Color color;
Balls(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getRadius() {
return radius;
}
public Color getColor() {
return color;
}
}
// Create 單詞拼錯了,不是creat,而是create.
//Balls 和 CreatBall類放在一個文件裡面的話,不能用public修飾,分開的話可以。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/306401.html