954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

New to java!

Hello again. So lately i've been learning java, and now i want to make a program but in this program i need to do something like in pascal record(i want to make an array, and in every element of this array i have a string and an int). I heared that in java is called class, but i can't find anywhere explained very clearly.

freakvista
Light Poster
39 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

Something like this?

public class ComponentTest{

    public static void main(String[] args){
        Component[] components = new Component[]{new Component("motherboard", 1234567),
                new Component("processor", 2345678), new Component("hard disk", 987654)};
        
        for(Component c : components){
            c.print();
        }

    }
    
    private static class Component{
        private String name;
        private long serialNumber;
        
        public Component(String name, long serialNumber){
            this.name = name;
            this.serialNumber = serialNumber;
        }
        
        public void print(){
            System.out.println(name + " - " + serialNumber);
        }
    }
}
peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 902
 

Classes are a way of representing objects in a program. The real world is made up of numerous things like tables, chairs, and couches. These objects have properties like height, width, and color. Classes allow you represent these objects by grouping variables together and developing methods to manipulate them in appropriate ways. I would suggest you check out this description for more information.

A very basic class to represent what you've described would look like this:

public class ExampleClass {

	// These variables are the class'
	private String classString;
	private int classInt;
	
	// This is the constructor for the class. You need to call it to create an instance of the class
	public ExampleClass(String yourString, int yourInt) {
		classString = yourString;
		classInt = yourInt;
	}
	
	// These methods let you access the variables stored in the class
	public String getString() {
		return classString;
	}
	
	public int getInt() {
		return classInt;
	}
}


This is by no means a complete explanation of classes nor a complete class, but hopefully it will help you get started!

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You