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<String> sports = new ArrayList<String>();
sports.add("Football");
sports.add("Boxing");
for(String sport : sports) {
System.out.println(sport);
}
//Major cities and the year they were founded
HashMap<String, Integer> majorCities = new HashMap<String, Integer>();
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));
}
}
}
网友评论