- Objects are instances of Classes, which are like a template of data (attributes) and functions (methods)
- Objects are created and their contents, which are pulled from the class, is used in code
public class Tennis { // class creation
public void printPlayers(){ // simple method
System.out.println("Nadal");
System.out.println("Federer");
System.out.println("Djokovic");
}
public static void main(String[] args){ // main class that runs
Tennis myObject = new Tennis(); // CREATING AN OBJECT FROM TENNIS CLASS
myObject.printPlayers(); // Use dot notation to reference methods/attributes from the class that the object is initialized from
}
}
Tennis.main(null);
- Extending another Class inherits all of the methods and attributes from that class.
- Class being extended is called the super class
- Class extending is called subclass
public class TennisTwo extends Tennis{ // extending Tennis class
public TennisTwo(){ // TennisTwo now has all of Tennis's methods
super();
}
public static void main(String[] args){ // main class that runs
TennisTwo myObjectTwo = new TennisTwo(); // CREATING AN OBJECT FROM TENNISTWO CLASS
myObjectTwo.printPlayers(); // Use dot notation to reference methods/attributes from the INHERITED class
}
}
TennisTwo.main(null);
Comparing Objects
- equals and hashCode methods can be used to compare objects
- equals method compares equality of two objects ### Example
import java.io.*;
class Pet {
String name;
int age;
String breed;
Pet(String name, int age, String breed)
{
this.name = name;
this.age = age;
this.breed = breed;
}
}
public class Main {
public static void main(String args[])
{
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
System.out.println(dog1.equals(dog2));
}
}
Main.main(null);
public int scoreGuess( String guess )
{
int val = 0;
int len = guess.length();
for( int i = 0; i <= secret.length()-len; i+=1)
{
String ck = secret.substring( i, i+len );
if( ck.equals(guess) )
val++;
}
return val*len*len;
}
public String findBetterGuess(String guess1, String guess2 )
{
int a = scoreGuess( guess1 );
int b = scoreGuess( guess2 );
if( a > b ) return guess1;
if( b > a ) return guess2;
if( guess1.compareTo( guess2 ) > 0 )
return guess1;
return guess2;
}