Java OOP

A class: is a set of instructions that describe how a data structure should behave.
A class constructor: creates instances. Every class has at least a constructor.
Object: is an instance of a class that stores the state of a class.
Instance variables: describe details of the object
Inheritance: is used to inherit or share behavior from another class. 'extends' keyword is used to indicate the inherit behavior

Example:
Animal.java
class Animal {

public void checkStatus() {

    System.out.println("Your pet is healthy and happy!");

}

}
Dog.java
class Dog extends Animal {

int age;

public Dog(int dogsAge) {

age = dogsAge;

}

public void bark(){
System.out.println("Woof!");
}

public void run(int feet){
System.out.println("Your dog ran" + feet + "feet!");
}

public int getAge(){
return age;}

public static void main(String[] args) {
        Dog spike = new Dog(2);
    spike.bark();
    spike.run(2);
    int spikeAge = spike.getAge();
    System.out.println(spikeAge);
    spike.checkStatus();

}

}

Data Structure:
ArrayList: stores a list of data
HashMap: stores keys and asscociated values like a dictionary

Example:
import java.util.*;

public class GeneralizationsD {
public static void main(String[] args) {
ArrayList sports = new ArrayList();
sports.add("Football");
sports.add("Boxing");

    for(String sport : sports) {
        System.out.println(sport);
    }

    //Major cities and the year they were founded
    HashMap majorCities = new HashMap();

    majorCities.put("New York", 1624);
    majorCities.put("London", 43);
    majorCities.put("Mexico City", 1521);
    majorCities.put("Sao Paulo", 1554);


    for (String city: majorCities.keySet()) {

        System.out.println(city + " was founded in " + majorCities.get(city));

    }



}

}

你可能感兴趣的:(Java OOP)