my cool blog

whats up

JAVA fundamentals AND JAVA HELLO HACKS • 5 min read

Description

Java fundamentals learning

Anatomy of a class

import java.util.Scanner;  

public class Dog {    //class is the blueprint, we use it to make objects, from class

    // In between brackets we define body of class, NEED what comments say

    // instance variables, WE ARE defining the attributes instances(objects) will have

    private String name;
    private String color;
    private String language;


    // constructors, WE use this to help build our object, FROM OUR instance variables
    public Dog(String initName, String initColor, String initLanguage) // can also be known as "setters"
    {
        this.name = initName;
        this.color = initColor;
        this.language = initLanguage;
    }

    public void setName(String name) { // ACTUAL setter method
        this.name = name;
    }

    // methods, THESE DEFINE what we do with our objects. PUBLIC methods can 
    //be called outside of class, private cannot.

    public void print() //getters to access our objects
    // This method will be used to see our objects,
    //VOID means that the method returns nothing but has meaningless effect,
    // like printing to screen 
    {
        System.out.println("Name: " + name);
        System.out.println("Color: " + color);
        System.out.println("Language " + language);
    }


    public static void main(String[] args) 
    {
        //This other method we will use for making dogs and using print method

        // calling our constructor to create our "dog" objects
        Scanner scanner = new Scanner(System.in);  
        Dog d1 = new Dog("Sam Fisher", "Green", "English"); 
        //calling print method
        d1.print();
        Dog d2 = new Dog("Kiryu Kazuma", "Red", "Japanese");
        d2.print();
        System.out.print("Enter new name for dog 1:");  
        String name = scanner.nextLine();
        d1.setName(name);


        d1.print();
    }
}

Dog.main(null); // activate the code
Name: Sam Fisher
Color: Green
Language English
Name: Kiryu Kazuma
Color: Red
Language Japanese
Enter new ame for dog 1:Name: cool
Color: Green
Language English

important information

“In general and definitely on the AP CSA exam, instance variables should be declared private. Think of private as like your diary. Only you should have direct access to it. Similarly, in Java a private instance variable can only be accessed by code in the class that declares the variable.”

Scroll to top