d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Newbie Question About "super" Classes..
12Next
Add Reply New Topic New Poll
Member
Posts: 5,913
Joined: May 6 2009
Gold: 0.00
Mar 10 2015 01:40pm
Hey, I dont understand why its needed to use a "super"class here... could some1 please explain? Its a program containing a GUI with 3 classes in it..


GUI with main..
Code
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.IOException;

import javax.swing.*;

public class GUI {

Person foundPerson;
Register reg;
JFrame guiFrame;
JPanel gridPanel;
JTextField firstNameField, lastNameField, numberField, messageField;
JLabel firstNameLbl, lastNameLbl, numberLbl, messageLbl;
JButton searchBtn, openBtn, saveBtn, addPostBtn, removePostBtn, editPostBtn, clearBtn;

public static void main(String[] args) {

new GUI();

}


public class InputListener implements ActionListener {

public InputListener() {

}

@Override
public void actionPerformed(ActionEvent event) {
//Do some shit with the input

if (event.getSource() == searchBtn) {
System.out.println("search");

//Discard option to remove Person
foundPerson = null;

//Try-catch statement to handle search
try {

//Save the found person in a reference variable
foundPerson = reg.search(firstNameField.getText(), lastNameField.getText(), numberField.getText());

//Fill in the blank fields with the found's info
firstNameField.setText( foundPerson.getFirstName() );
lastNameField.setText( foundPerson.getLastName() );
numberField.setText( foundPerson.getNumber() );

//Display messages
messageField.setText("Person found.");
System.out.println( foundPerson );

} catch (SearchException e) {

//Display error messages
System.out.println( e.getMessage() );
messageField.setText("Person not found.");
}

}

else if (event.getSource() == openBtn) {
System.out.println("openReg");

//Discard option to remove Person
foundPerson = null;

//Ask for filename
String filename = JOptionPane.showInputDialog(null, "Specify the file path:");

//Try to open file
try {

//Read from file
reg.readRegisterFromFile(filename);

//Show number of Persons currently in the memory
messageField.setText("Persons: " + reg.getRegisterLength());

} catch (IOException e) {

//Error message
JOptionPane.showMessageDialog(null, "File not found, proceeding with program.");
}
}

else if (event.getSource() == saveBtn) {
System.out.println("saveReg");

//Discard option to remove Person
foundPerson = null;

//Ask for output filename
String filename = JOptionPane.showInputDialog(null, "Specify the file path:");

try {

//Save to file
reg.saveRegisterToFile(filename);
messageField.setText("Persons: " + reg.getRegisterLength());

} catch (IOException e) {
//Display error messages to console
e.printStackTrace();
}
}

else if (event.getSource() == addPostBtn) {

//Discard option to remove Person
foundPerson = null;

String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String number = numberField.getText();

//Check if all fields are filled with sth
if ( !firstName.equals("") && !lastName.equals("") && !number.equals("") ) {

//Try to add the person
reg.addPerson(firstName, lastName, number);
System.out.println("added post");
messageField.setText("Persons: " + reg.getRegisterLength());

}

else messageField.setText("No blank fields allowed.");

}

else if (event.getSource() == removePostBtn) {
System.out.println("removePost");

if (foundPerson != null) {

//Remove the person
reg.removePerson( foundPerson );

//Discard option to remove Person
foundPerson = null;

//Reset the fields
firstNameField.setText("");
lastNameField.setText("");
numberField.setText("");
}
}

else {
System.out.println("clear");

//Discard option to remove Person
foundPerson = null;

//Reset the fields
firstNameField.setText("");
lastNameField.setText("");
numberField.setText("");

//Display number of Persons in memory
messageField.setText("Persons: " + reg.getRegisterLength());
}
}

}

public GUI() {

reg = new Register();

int width = 550, height = 200;

guiFrame = new JFrame();
guiFrame.setSize(width, height);
guiFrame.setTitle("Search");
guiFrame.setLocationRelativeTo(null);

gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(4, 4));
guiFrame.add(gridPanel);

//Creating labels
firstNameLbl = new JLabel();
firstNameLbl.setText("First name: ");
firstNameLbl.setHorizontalAlignment(SwingConstants.RIGHT);

lastNameLbl = new JLabel();
lastNameLbl.setText("Last name: ");
lastNameLbl.setHorizontalAlignment(SwingConstants.RIGHT);

numberLbl = new JLabel();
numberLbl.setText("Phone number: ");
numberLbl.setHorizontalAlignment(SwingConstants.RIGHT);

messageLbl = new JLabel();
messageLbl.setText("Message: ");
messageLbl.setHorizontalAlignment(SwingConstants.RIGHT);

//Creating text fields
firstNameField = new JTextField();
lastNameField = new JTextField();
numberField = new JTextField();
messageField = new JTextField();
messageField.setText("Persons: 0");
messageField.setEditable(false);

//Create InputListener
InputListener AL = new InputListener();

//Creating buttons
searchBtn = new JButton("Search");
searchBtn.addActionListener(AL);

openBtn = new JButton("Open register");
openBtn.addActionListener(AL);

saveBtn = new JButton("Save register");
saveBtn.addActionListener(AL);

addPostBtn = new JButton("Add post");
addPostBtn.addActionListener(AL);

removePostBtn = new JButton("Remove post");
removePostBtn.addActionListener(AL);

clearBtn = new JButton("Clear fields");
clearBtn.addActionListener(AL);

//Adds everything to the grid
gridPanel.add(firstNameLbl);
gridPanel.add(firstNameField);
gridPanel.add(searchBtn);
gridPanel.add(openBtn);

gridPanel.add(lastNameLbl);
gridPanel.add(lastNameField);
gridPanel.add(clearBtn);
gridPanel.add(saveBtn);


gridPanel.add(numberLbl);
gridPanel.add(numberField);
gridPanel.add(addPostBtn);
gridPanel.add(removePostBtn);


//gridPanel.add(editPostBtn);
gridPanel.add(messageLbl);
gridPanel.add(messageField);

guiFrame.setVisible(true);
guiFrame.setResizable(false);

}
}


Person class
Code
public class Person implements Comparable<Person> {
private String firstNameP, lastNameP, numberP;

public Person(String firstName, String lastName, String number) {
setPerson(firstName, lastName, number);
}

public void setPerson(String firstName, String lastName, String number) {
firstNameP = firstName;
lastNameP = lastName;
numberP = number;
}


/* IMPLEMENTATION OF COMPARABLE */

public int compareTo(Person p) {

if (firstNameP.equals(p.getFirstName())) return lastNameP.compareTo(p.getLastName());

else return firstNameP.compareTo(p.getFirstName());
}

public int compareNumberTo(Person p) {
return numberP.compareTo(p.getNumber());
}

public String toString() {
return firstNameP + " " + lastNameP + " " + numberP;
}


/* BASIC GETTERS */

public String getFirstName() {
return firstNameP;
}

public String getLastName() {
return lastNameP;
}

public String getNumber() {
return numberP;
}
}


register class
Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.swing.JOptionPane;


public class Register {


private ArrayList<Person> register;

public Register() {
register = new ArrayList<Person>();
}

public void readRegisterFromFile(String file) throws IOException {

// Open input file for reading
BufferedReader infile = new BufferedReader(new FileReader(
"H:\\Java\\lab6\\" + file));

String inline;

// Read the infile line-by-line
while ((inline = infile.readLine()) != null) {
// Extract each word from the line into an array of Strings
String[] words = inline.split("\\s+");

//Check if the first name, last name, and phone number exists
if (words.length == 3) {

Person tempPerson = new Person(words[0], words[1], words[2]);
boolean isInRegister = false;

//Compare the entry to every person in the register
for (int i = 0; i < register.size(); i++) {
if ( tempPerson.compareTo( register.get(i) ) == 0 || tempPerson.compareNumberTo( register.get(i) ) == 0 ) {
isInRegister = true;

}
}
//Add the person and sorts the register
if (!isInRegister) {
register.add( tempPerson );
Collections.sort(register);
}

}

}

// Close the input file
infile.close();
}

//Returns the length of the register
public int getRegisterLength() {
return register.size();
}

//Saves everything in the register to the file
public void saveRegisterToFile(String file) throws IOException {
PrintWriter outfile = new PrintWriter(file);

for (int i = 0; i < register.size(); i++) {

outfile.println( register.get(i) );
}

outfile.close();

}

//Adds a person to the register
public void addPerson(String firstName, String lastName, String number) {

Person tempPerson = new Person(firstName, lastName, number);

for (int i = 0; i < register.size(); i++) {
//Check if the person already exists in the register
if ( tempPerson.compareTo( register.get(i) ) == 0 || tempPerson.compareNumberTo( register.get(i) ) == 0 ) {
JOptionPane.showMessageDialog(null, "Person is already in the register.");
return;
}

}

//Add the person and sorts the register
register.add(tempPerson);
Collections.sort(register);

}

public void removePerson(Person thePerson) {

for (int i = 0; i < register.size(); i++) {
//Removes the person from the register if it exists
if (thePerson == register.get(i)) register.remove(i);
}

Collections.sort(register);
}

public Person search(String firstName, String lastName, String number) throws SearchException{

//Check if full name or number exists
if ( ( !firstName.equals("") && !lastName.equals("") ) || !number.equals("") ) {

Person tempPerson = new Person(firstName, lastName, number);
//If the number doesn't exist, search by name to find it
if (number.equals("")) {

for (int i = 0; i < register.size(); i++) {

if (tempPerson.compareTo(register.get(i)) == 0) return register.get(i);

}

}

//If the full name doesn't exist, search by number to find it
else if (firstName.equals("") && lastName.equals("")) {

for (int i = 0; i < register.size(); i++) {
if (tempPerson.compareNumberTo(register.get(i)) == 0) return register.get(i);
}

}

//If full name and number exists (meaning the person will be found if the information completely matches)
else {
for (int i = 0; i < register.size(); i++) {
if (tempPerson.compareTo(register.get(i)) == 0 && tempPerson.compareNumberTo(register.get(i)) == 0) return register.get(i);
}
}
}
//Throws exception if not enough information is given to find a person
throw new SearchException("Search failed.");

}
}

SearchExpection class
Code
public class SearchException extends Exception {
public SearchException(String message) {
super(message);
}
}


SearchExpection is really confusing to me... from what I understand.. I use that one to create an errormessage and avoiding crashing the program.. but why do I need it to be a superclass?


What does the program?
The program wants u to write in a txt file with first name, last name and phone number... and then the program search if the person exists in the txt file.. and u can add ppl to the txt file and save to a new txt file and so on.. the program is working fine.. but I dont understand the the class "SearchExpection" which Ive said earlier..

This post was edited by bomben on Mar 10 2015 01:45pm
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Mar 10 2015 02:19pm
Quote
SearchExpection is really confusing to me... from what I understand.. I use that one to create an errormessage and avoiding crashing the program.. but why do I need it to be a superclass?


it's not a super class; it's a subclass.
when you find a search problem, you want to throw it and let it bubble up. the problem is that you can't throw just anything. you have to throw something that's a subclass of Throwable. Exception is the right choice. personally, i often extend RuntimeException just so i don't have to declare every method as throwing it.
Member
Posts: 5,913
Joined: May 6 2009
Gold: 0.00
Mar 10 2015 03:01pm
Quote (carteblanche @ Mar 10 2015 09:19pm)
it's not a super class; it's a subclass.
when you find a search problem, you want to throw it and let it bubble up. the problem is that you can't throw just anything. you have to throw something that's a subclass of Throwable. Exception is the right choice. personally, i often extend RuntimeException just so i don't have to declare every method as throwing it.


If its not a superclass then why is there

super(message);

?
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Mar 10 2015 03:12pm
Quote (bomben @ Mar 10 2015 05:01pm)
If its not a superclass then why is there

super(message);

?


think about it for a minute. do you know what that statement does?

http://docs.oracle.com/javase/tutorial/java/IandI/super.html
Member
Posts: 5,913
Joined: May 6 2009
Gold: 0.00
Mar 10 2015 03:26pm
Quote (carteblanche @ Mar 10 2015 10:12pm)
think about it for a minute. do you know what that statement does?

http://docs.oracle.com/javase/tutorial/java/IandI/super.html


:O that link was really informative!

Basicly...

My class "SearchExpection" uses "message" but where do it find the message?
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Mar 10 2015 03:33pm
Quote (bomben @ Mar 10 2015 05:26pm)
My class "SearchExpection" uses "message" but where do it find the message?


hence inheriting from Exception

http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html

Quote
Methods inherited from class java.lang.Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString


since it inherits from Throwable, i suggest reading its documentation as well

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html

tutorial on exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/

This post was edited by carteblanche on Mar 10 2015 03:37pm
Member
Posts: 5,913
Joined: May 6 2009
Gold: 0.00
Mar 10 2015 04:01pm
Quote (carteblanche @ Mar 10 2015 10:33pm)
hence inheriting from Exception

http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html



since it inherits from Throwable, i suggest reading its documentation as well

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html

tutorial on exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/


oh okey, so basicly "SearchException" makes so I can run my program without it crashing..

thanks a lot buddy

This post was edited by bomben on Mar 10 2015 04:01pm
Member
Posts: 1,995
Joined: Jun 28 2006
Gold: 7.41
Mar 10 2015 04:01pm
Quote (carteblanche @ Mar 10 2015 04:33pm)

since it inherits from Throwable, i suggest reading its documentation as well


I am going to be that guy and point out that you don't inherit the interface, but implement it. You inherit through derivation. So a class can inherit from some base class, or even an interface can inherit from some base interface. But a class does not inherit from an interface. It provides the implementation for the interface.

Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Mar 10 2015 04:08pm
Quote (Minkomonster @ Mar 10 2015 06:01pm)
I am going to be that guy and point out that you don't inherit the interface, but implement it. You inherit through derivation. So a class can inherit from some base class, or even an interface can inherit from some base interface. But a class does not inherit from an interface. It provides the implementation for the interface.


as oddly as it's named, Throwable is a class, not an interface.
Member
Posts: 1,995
Joined: Jun 28 2006
Gold: 7.41
Mar 10 2015 04:17pm
Quote (carteblanche @ Mar 10 2015 05:08pm)
as oddly as it's named, Throwable is a class, not an interface.


Fucking Java. Stick to your own damn naming conventions.
Go Back To Programming & Development Topic List
12Next
Add Reply New Topic New Poll