90 likes | 323 Views
Class. Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default one for you. Order of Class Composition: * Import statement if needed p ublic class ClassName
E N D
Class Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default one for you. Order of Class Composition: * Import statement if needed • public class ClassName • private Field data (instance variables) • public Constructor (method that creates the object) • public Methods ( get and set the instance variables and other actions as necessary)
Instance Variables Properties of the object. What it knows about itself. Created in a field so also called field data private String color; private int legs; private String name; I know my color, how many legs I have and my name.
CONSTRUCTOR public className() { Assign instance variables here } public Bug() { String color = “red”; int legs = 6; String name = “Beetle”; }
Parameter ( ) (football) Supplies extra information to a method that it needs to execute. If it doesn’t need any it is blank. Required for constructors & all methods. public Bug() { // constructor public static void main(String[]args) { // method public void setName(“String name”); // method
Classes create objects from the constructor with the word new public Bug() { String color = “red”; int legs = 6; String name = “Beetle”; } Default Constructor Bug b = new Bug(); Constructor that requires parameter info. when created. public Bug(String c, int l, String n) { color = c; legs = l; name = n; } Bug b = new Bug(“Red”, 6, “Beetle”); (String, int, String)
Methods Accessor Methods: Access information from our instance variables. Instance variable: name name is a String public String getname() { return name; } Return methods must specify what data type they are returning in the method header.
Mutator Methods Change information in our instance variables. Called setters. Instance Variable name public void setName(String n) { name = n; } Doesn’t return anything so it is void. Method that will set the instance variable for name to what is passed through the parameter when the method is called.
Objects call their method with dot operator. Bug b = new Bug(); // b is the object public void setName(String n); // is the method So when you call the method you do the following: b.setName(“Harry”); // object.method System.out.println(b.getname()); //prints Harry
Scanner Class import java.util.Scanner; // util package Constructor: public Scanner(Input Source) So to create a Scanner you do the following: Scanner sc = new Scanner(System.in); Scanner methods: sc.nextInt() stores ints sc.nextDouble() stores doubles sc.nextLine() stores next line as string sc.next() stores next as string