Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Alan Greenspan
Jun 17, 2001

rotor posted:

You won't be able to write to it, IIRC.

http://forum.java.sun.com/thread.jspa?threadID=300557&start=45&tstart=-1

Someone developed a cute hack I use to modify the classpath at runtime for plugin reasons.

Adbot
ADBOT LOVES YOU

zootm
Aug 8, 2006

We used to be better friends.

Alan Greenspan posted:

http://forum.java.sun.com/thread.jspa?threadID=300557&start=45&tstart=-1

Someone developed a cute hack I use to modify the classpath at runtime for plugin reasons.
For what it's worth I think rotor meant you couldn't write to locations on the classpath through the classpath/ClassLoader system itself, rather than talking about modifying the classpath at runtime. That's a neat trick though, a few systems do things like that and it never occurred to me that it wouldn't be trivial.

Alan Greenspan
Jun 17, 2001

Sweet and simple question about writing your own GUI controls.

I have a custom control that prints "Help me COC :(" by extending JPanel and overwriting

code:
public void paintComponent(Graphics g2)
Now I have a library that zooms stuff on the screen.

When I directly write to g2 the zoomed text looks great.



I used this code:

code:
public void paintComponent(Graphics g)
{
   g.setColor(Color.RED);
   g.fillRect(0, 0, getWidth(), getHeight());
   g.setColor(Color.BLACK);
   g.drawString("Help me COC :(", 20, 20);
}
Now the problem is that I don't have just 1 COC control but maybe like 50000 so drawing right to the screen graphics context is way too slow. I need to paint elsewhere and copy the "elsewhere" to the screen in one go.

code:
public void paintComponent(Graphics g)
{
   BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
   Graphics2D g2 = (Graphics2D) img.getGraphics();
   
   g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
   g2.setColor(Color.RED);
   g2.fillRect(0, 0, getWidth(), getHeight());
   g2.setColor(Color.BLACK);
   g2.drawString("Help me COC :(", 20, 20);
   
   img.flush();
   
   g.drawImage(img, 0, 0, null);
}


Now zooming does not work anymore. I suspect it's because I write to an image in the second case and it's pixels are fixed once written.

Any suggestions? Why are there differences between the Graphics context I get passed as the argument to the function and the one I create myself. What are these differences? Where should I draw to offscreen? How do I get a Graphics context that's equal to the one from the argument but doesn't directly write to the screen? Why is the zoomed text fine if directly written to the screen? Just what the hell is going on here, I appreciate any speculation. :(

Alan Greenspan
Jun 17, 2001

OK, I'm pretty sure this is what happens.

1. I write my stuff in my BufferedImage
2. I drawImage my BufferedImage to the Graphics context from the argument
3. The zoom kicks in and uses a method like Graphics2D::scale on the context
4. My drawn image pixelates because the scale method only sees the image and not the operations that created the image

:smithicide:

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome

Alan Greenspan posted:

OK, I'm pretty sure this is what happens.

1. I write my stuff in my BufferedImage
2. I drawImage my BufferedImage to the Graphics context from the argument
3. The zoom kicks in and uses a method like Graphics2D::scale on the context
4. My drawn image pixelates because the scale method only sees the image and not the operations that created the image

:smithicide:

right. You have to draw a fresh image every time you zoom. One thing you can try is rendering the maximally zoomed-in image at start-up and rendering scaled-down versions of it as events warrant. There's really no free lunch when it comes to rendering high-quality zoomed-in text, you just shuffle the work around.

rotor fucked around with this message at 21:44 on Mar 4, 2008

FuzzyBuddha
Dec 7, 2003

Leehro posted:

after a quick look at the features of JCreator Lite, I can point out a few things that NetBeans has that it doesn't:

...

Try NetBeans for a day or even an hour. It's easy to get up and running.
Ok, a bit late but... I want to thank you for this suggestion, if for no other reason than it tags errors as I type. I'm a horrible typer and this has already saved a lot of headache.

zootm
Aug 8, 2006

We used to be better friends.

FuzzyBuddha posted:

Ok, a bit late but... I want to thank you for this suggestion, if for no other reason than it tags errors as I type. I'm a horrible typer and this has already saved a lot of headache.
Using "ctrl-space" you'll probably never have to type anything again. :)

Leehro
Feb 20, 2003

"It's a gaming ship."

FuzzyBuddha posted:

Ok, a bit late but... I want to thank you for this suggestion, if for no other reason than it tags errors as I type. I'm a horrible typer and this has already saved a lot of headache.

Yeah it's a nice set of tracks to keep you on the right path.

zootm posted:

Using "ctrl-space" you'll probably never have to type anything again. :)

I didn't know about this, and the times when I wanted the autocomplete to kick in, I'd usually backspace over the ., type it again, and wait. Thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
If I have an ArrayList of Objects, and I want to sort them by one of the fields (string) in the Object, how would I do that?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
If you can change your objects you can have them implement the Comparator interface. Now you can use the sort the function in java.util.Collections class.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MEAT TREAT posted:

If you can change your objects you can have them implement the Comparator interface. Now you can use the sort the function in java.util.Collections class.

Ok cool, that led me to this

code:
	private class AlphaComparator implements Comparator {
		public String compare(Object obj1, Object obj2) {
			Product prod1 = (Product) obj1;
			Product prod2 = (Product) obj2;
			String name1 = (String) prod1.name;
			String name2 = (String) prod2.name;
			return name1.compareTo(name2);
		}
	}
What's wrong with my code? It's telling me type mismatch, cannot convert from int to string.

fletcher fucked around with this message at 04:49 on Mar 5, 2008

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
compare should return an int, not a String.

Try:
code:
private class AlphaComparator implements Comparator {
		public int compare(Object obj1, Object obj2) {
			Product prod1 = (Product) obj1;
			Product prod2 = (Product) obj2;
			String name1 = (String) prod1.name;
			String name2 = (String) prod2.name;
			return name1.compareTo(name2);
		}
	}

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Hah well I feel like an rear end. Thank you! Works great now.

the onion wizard
Apr 14, 2004

fletcher posted:

Ok cool, that led me to this

What's wrong with my code? It's telling me type mismatch, cannot convert from int to string.

What type is name in the Product class? If it's a String already, you don't need those casts to String. It's only a minor issue, but every time I see stuff like that at work I die a little.


Along these lines, is all programming in a corporate environment completely soul crushing, or is there hope?

Brain Candy
May 18, 2006

triplekungfu posted:

What type is name in the Product class? If it's a String already, you don't need those casts to String. It's only a minor issue, but every time I see stuff like that at work I die a little.

String is final, so name is either a String or an Object (or CharSequence or Comparable<String>(!)). :suicide:

Brain Candy fucked around with this message at 12:56 on Mar 5, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

triplekungfu posted:

What type is name in the Product class? If it's a String already, you don't need those casts to String. It's only a minor issue, but every time I see stuff like that at work I die a little.

Thanks for the tip. Normally I'd try it both ways, but not when I needed to get that code checked in ASAP. I was just copying the example code from the link up above.

fletcher fucked around with this message at 15:21 on Mar 5, 2008

GameCube
Nov 21, 2006

Ugh, I feel like a retard asking this here, as it seems like a question for Google, but either this is more complicated than I expected or Google's just being stupid.

I've got an assignment to write a simple paint program using a Swing panel, where you left-click and drag to paint and right-click and drag to erase. I got the left-click just fine with a MouseDragged event, but now I can't figure out how to do something different for a right-button drag. Once I figure out how to check for the right button in the first place, I should be able to throw some if statements around stuff and get the rest on my own. Any advice?

EDIT: Never mind, got it! Was busy messing with some bitwise crap I found on this page, when right above that was an easy set of boolean methods to use. http://www.leepoint.net/notes-java/GUI-lowlevel/mouse/20mousebuttons.html

GameCube fucked around with this message at 02:27 on Mar 6, 2008

roadhead
Dec 25, 2001

I'd like to Parse an HTML-formatted String (so I can get tables at a certain width, columns either justified or centered, other simple stuff).

Once this data is "rendered" I need to pop it back into a plain String (still formatted using absolute spaces and cr/lf) to feed it to a receipt printer.

Am I crazy?

I have to make a bunch of these receipts, and they have to dynamically adjust their width based on the printer model. The end result would be exactly like what you get if you rendered the HTML in a browser, then copied and pasted it into a non-HTML aware application.


So, is this going to be possible with the Java standard library? I'm using javax.swing.text.html.HTMLDocument right this second.

Any other ideas ?

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome

roadhead posted:

I'd like to Parse an HTML-formatted String (so I can get tables at a certain width, columns either justified or centered, other simple stuff).

Once this data is "rendered" I need to pop it back into a plain String (still formatted using absolute spaces and cr/lf) to feed it to a receipt printer.

Am I crazy?

I have to make a bunch of these receipts, and they have to dynamically adjust their width based on the printer model. The end result would be exactly like what you get if you rendered the HTML in a browser, then copied and pasted it into a non-HTML aware application.


So, is this going to be possible with the Java standard library? I'm using javax.swing.text.html.HTMLDocument right this second.

Any other ideas ?

If I understand you correctly (never a safe bet) it seems that html has nothing do do with this. You have some string data you want formatted nicely on fixed-width font printers, and you're trying to abuse an html layout engine to do this.

My advice would be to look around for something like a java curses library or just write your own - formatters like this are pretty common homework for programming classes, so I'd be surprised if you can't find some kind of libraries floating around.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rotor posted:

If I understand you correctly (never a safe bet) it seems that html has nothing do do with this. You have some string data you want formatted nicely on fixed-width font printers, and you're trying to abuse an html layout engine to do this.

My advice would be to look around for something like a java curses library or just write your own - formatters like this are pretty common homework for programming classes, so I'd be surprised if you can't find some kind of libraries floating around.

There is a mature Java curses lib, and it's pretty awesome. A guy at work popped out a tabular pgsql database stats browser with it in a day.

I'm curious why roadheads' implementation has to be in java and not something like LaTeX or PS. Those languages are made for type-setting.

roadhead
Dec 25, 2001

TRex EaterofCars posted:

There is a mature Java curses lib, and it's pretty awesome. A guy at work popped out a tabular pgsql database stats browser with it in a day.

I'm curious why roadheads' implementation has to be in java and not something like LaTeX or PS. Those languages are made for type-setting.

It has to be in Java because thats what we use, the whole project is in Java. Seven years in the making, the end-all be-all of hardware store software. AP, AR, GL, PoS, Inventory, Payroll etc. I'm just one person out of many, and this is what I've been stuck with lately :)

Some of the foundation for this area has already been laid and a single "receipt" template completed, but the formatting was all in lots and lots of lines of actual Java code, no template being stored in the database at all. I was hoping to write something that would lay out my template, put it to a formatted string, with several "replaceable" variables for the content that is transmitted from the PoS terminal. That part is already in place in our String utilities, so I don't have to worry about that, just the layout part :)

Since a customer could have any model of printer, the width of the form is defined run-time, which is why I wanted to use HTML and set the width of the table with a resolvable variable.

Does this explain it better at all ?

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome

roadhead posted:

Since a customer could have any model of printer, the width of the form is defined run-time, which is why I wanted to use HTML and set the width of the table with a resolvable variable.

Does this explain it better at all ?

yeah. You'll kill yourself trying to make the html layout engine do this properly. Dig up a java curses library, it shouldn't be too hard.

Unless your input is HTML ... in which case my advice would be to strip out the html and then find a java curses library.

I just don't see how you're going to take an html renderer and get it to spit out fixed-width font layouts in any kind of reasonable way. This is what console-based apps are really good at, so I'd go back and look at the display libraries for those - i.e. curses.

Emo.fm
Jan 2, 2007
I'm writing a program (yes, homework for intro CS) that plays a quick card game between two computer players and then returns who won (player 1 or 2, it's a random game of luck so theoretically I should be able to run it 1000000 times and see 50/50 winning percentages). I believe my code is correct, and I can run it as many times as I want with no exceptions if I actually run it repeatedly by hand -- but if I insert a for loop to get it to run multiple trials, I invariably end up with an array index out of bounds exception. I'm really confused by this because all of the variables (arrays of cards, stuff like that) are declared either in the for loop or the method called from within the for loop. What kinds of things should I be looking for? What could cause the program to screw up when run multiple times within itself, when I can run it so many times from outside with no incidents, so to speak?

Incoherence
May 22, 2004

POYO AND TEAR

Emo.fm posted:

I'm writing a program (yes, homework for intro CS) that plays a quick card game between two computer players and then returns who won (player 1 or 2, it's a random game of luck so theoretically I should be able to run it 1000000 times and see 50/50 winning percentages). I believe my code is correct, and I can run it as many times as I want with no exceptions if I actually run it repeatedly by hand -- but if I insert a for loop to get it to run multiple trials, I invariably end up with an array index out of bounds exception. I'm really confused by this because all of the variables (arrays of cards, stuff like that) are declared either in the for loop or the method called from within the for loop. What kinds of things should I be looking for? What could cause the program to screw up when run multiple times within itself, when I can run it so many times from outside with no incidents, so to speak?
Unless you're catching the exception and eating it, the exception message should specify exactly what the offending index is, and possibly what line it occurred on.

Off the top of my head, make sure you realize that Java (and C and its derivatives) arrays are 0-based, and an array of N elements has valid indices from 0 to N-1 inclusive (and index N will cause an exception).

It has nothing to do with your for loop, which I assume is just counting runs and isn't actually doing anything in the body of the loop, except that running it 1 million times makes it more likely that a bug based on random input (and presumably there's random input somewhere in your program) will manifest itself.

It may be worth posting your code, or at least posting the exception message.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I agree with posting your code. Your problem doesn't make much sense, it should work.

Incoherence
May 22, 2004

POYO AND TEAR

MEAT TREAT posted:

I agree with posting your code. Your problem doesn't make much sense, it should work.
I have no doubt that there's an error in it, but I'm guessing that it has nothing to do with the loop. Start by looking at the actual exception message, and be glad you're not writing C and just looking at the words "Segmentation Fault".

Leehro
Feb 20, 2003

"It's a gaming ship."
Yeah, either your variables aren't getting reset -or- you're not getting the random number range right.

If you have a debugger, you can find this easily.

dizzywhip
Dec 23, 2005

dizzywhip fucked around with this message at 20:16 on Nov 9, 2020

10011
Jul 22, 2007
You need to create the array first, then initialise its elements:

code:
IntTuple[] changeArray = new IntTuple[arraySize];
for (int i = 0; i < arraySize; ++i)
    changeArray[i] = new IntTuple(arrayRows);

dizzywhip
Dec 23, 2005

dizzywhip fucked around with this message at 20:17 on Nov 9, 2020

fret logic
Mar 8, 2005
roffle
This is kind of an odd question because it's about my approach and not a bug in the code. I'm trying to do different projects to learn Java and C, and one of my Java projects was to build a very simple fighting RPG from the ground up as I learn. So tonight I was messing around with getting it to let the player choose which class to play and then shows them the stats when they pick.

My question is, how terrible did I go about this? I don't want to get in the habit of a bad approach to different problems.

code:
public class Player 
{
	private int hitpoints;
	private int strength;
	private int defense;
	private String playerclass;
	
	public Player(int choice)
	{
		switch (choice)
		{
		case 1: playerclass = "Fighter";
				strength = 20;
				defense = 18;
				hitpoints = 50;
				break;
		case 2: playerclass = "Archer";
				strength = 15;
				defense = 22;
				hitpoints = 30;
				break; 
		}
	}
	
	
	public void updateStats()
	{
		System.out.println("Player class: " + playerclass);
		System.out.println("Strength: " + strength);
		System.out.println("Defense: " + defense);
		System.out.println("Hitpoints: " + hitpoints);
	}
	
}
code:
import java.util.*;
public class GameLoop
{
	
	Scanner getinput;
	static Player newplayer;
	static GameLoop game;
	
	public static void main(String[] args)
	{
		game = new GameLoop();
		newplayer = new Player(game.choosePlayer());
		newplayer.updateStats();
	}
	
	public int choosePlayer()
	{
		
		int choose; 
		choose = 3; 
		
		getinput = new Scanner(System.in);
		
		while ((choose != 1) && (choose != 2)) {
			System.out.println("Choose a player class: ");
			System.out.println("1. Fighter");
			System.out.println("2. Archer");
			choose = getinput.nextInt();
			
			if ((choose != 1) && (choose != 2)) {
				System.out.println("That's not a correct choice");
			}
		}
		return choose;
		
		
	}
	
}
So how lovely is my approach to this simple program? Too complex? Improper use of O-O?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Well your approach isn't very OO yet. I'll try to critique your Player class first.

You are limiting yourself by defining the 2 playerclasses. A much more robust constructor would be this.

code:
public Player (int hitpoints, int strength, int defense, String playerclass){
    this.hitpoints = hitpoints;
    this.strength= strength
    this.defense, = defense, ;
    this.playerclass = playerclass;
}
Now in your main program you can create as many different characters classes as you wish or even variations of the same class. Imagine a Fighter with less hit points and higher defense. You could even allow the user to create their own class by giving them lets say 100 points to distribute between Strength, Defense, and HP. You can still use your approach and have some predefined classes that they can choose from. The choice is up to you but this constructor allows more flexibility later on.

Your method updateStats should be changed to override the toString method since you are not actually updating any of the stats.

I think the only method that is missing from the Player class is a combat method where he can do damage to another Player.

I'll let someone else comment on your GameLoop class because I have to run.

fret logic
Mar 8, 2005
roffle

MEAT TREAT posted:

Well your approach isn't very OO yet. I'll try to critique your Player class first.

You are limiting yourself by defining the 2 playerclasses. A much more robust constructor would be this.

code:
public Player (int hitpoints, int strength, int defense, String playerclass){
    this.hitpoints = hitpoints;
    this.strength= strength
    this.defense, = defense, ;
    this.playerclass = playerclass;
}
Now in your main program you can create as many different characters classes as you wish or even variations of the same class. Imagine a Fighter with less hit points and higher defense. You could even allow the user to create their own class by giving them lets say 100 points to distribute between Strength, Defense, and HP. You can still use your approach and have some predefined classes that they can choose from. The choice is up to you but this constructor allows more flexibility later on.

Your method updateStats should be changed to override the toString method since you are not actually updating any of the stats.

I think the only method that is missing from the Player class is a combat method where he can do damage to another Player.

I'll let someone else comment on your GameLoop class because I have to run.

Thanks for the advice, the bit about making a more robust Player object is very helpful. I spent a long time thinking about how to set that up and this clears it up for me :)

This short program was a quick attempt at displaying some information based on user selection using a setup kind of like I would if I was making the actual game. I will be making the game at some point as a larger project, but at the moment I'm just making random pieces to have something to do.

fnordcircle
Jul 7, 2004

PTUI
Any suggestions for online Java tutorials for a beginning programmer? I've got a good book but a friend of mine who is on deployment in Afganistan would like to try learning Java along with me but he can't exactly go to Barnes & Nobles. Honestly looking through Java tutorials with google I'm not finding anything that equates to 'Java for Dummies' which is probably what he wants.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
There is Bruce Eckel's Thinking in Java which is available online for free. I've been reading his C++ book and I like it very much. I can't think of any Java tutorials, but frankly you should stay away from them. Tutorials rarely cover any subject in depth so there usefulness is limited.

fret logic
Mar 8, 2005
roffle

MEAT TREAT posted:

There is Bruce Eckel's Thinking in Java which is available online for free. I've been reading his C++ book and I like it very much. I can't think of any Java tutorials, but frankly you should stay away from them. Tutorials rarely cover any subject in depth so there usefulness is limited.

That's the book I use and I'm really pleased with it for being free of charge and all.

Dresden
Jun 23, 2004

Skate it off, skate it off.
I have an issue with request.getParameter when I am trying to pass in a url encoded parameter. getParameter always assumes that I want the data decoded, but is there any way to get the parameter if I don't want the parameter decoded, rather I would like to decode it myself later?

What I have done right now is user getQueryString and parse out the particular parameter I want, but I'd like to know if there is a less hacky way to do this.

The particular issue is that I am passing in a path, but sometimes the path may contain the %2F character, which is the \ character, ruining the path.

Anyone know?

ynef
Jun 12, 2002

fret logic posted:

Thanks for the advice, the bit about making a more robust Player object is very helpful. I spent a long time thinking about how to set that up and this clears it up for me :)

This short program was a quick attempt at displaying some information based on user selection using a setup kind of like I would if I was making the actual game. I will be making the game at some point as a larger project, but at the moment I'm just making random pieces to have something to do.

Depending on your game and what it will support in the future, I'd say that Player should be an abstract class and that you should subclass it with a Fighter and an Archer class. The reason (which may not be valid in your case) is that, for instance, you'll want to give all archers a bonus for ranged weapons or restrict so that fighters can't used crossbows (whatever). If you stick to using conditional statements (if, switch) then you will quickly get a headache trying to code all these rules that will be easily avoided if you just go with the subclassing. Also, the constructor for each class will be very simple and you can still keep the toString() method (which you should use) in the abstract Player class. Adding more types of Player will be ridiculously easy too.

If you go that route, keep in mind that you need to change all attributes in Player to "protected" for subclasses to access them.

fret logic
Mar 8, 2005
roffle

ynef posted:

Depending on your game and what it will support in the future, I'd say that Player should be an abstract class and that you should subclass it with a Fighter and an Archer class. The reason (which may not be valid in your case) is that, for instance, you'll want to give all archers a bonus for ranged weapons or restrict so that fighters can't used crossbows (whatever). If you stick to using conditional statements (if, switch) then you will quickly get a headache trying to code all these rules that will be easily avoided if you just go with the subclassing. Also, the constructor for each class will be very simple and you can still keep the toString() method (which you should use) in the abstract Player class. Adding more types of Player will be ridiculously easy too.

If you go that route, keep in mind that you need to change all attributes in Player to "protected" for subclasses to access them.

That does make sense but I'm a little ashamed to say I had to look up how to create a subclass, since I haven't learned it yet. Thanks for the help!

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

ynef posted:

Depending on your game and what it will support in the future, I'd say that Player should be an abstract class and that you should subclass it with a Fighter and an Archer class. The reason (which may not be valid in your case) is that, for instance, you'll want to give all archers a bonus for ranged weapons or restrict so that fighters can't used crossbows (whatever). If you stick to using conditional statements (if, switch) then you will quickly get a headache trying to code all these rules that will be easily avoided if you just go with the subclassing. Also, the constructor for each class will be very simple and you can still keep the toString() method (which you should use) in the abstract Player class. Adding more types of Player will be ridiculously easy too.

If you go that route, keep in mind that you need to change all attributes in Player to "protected" for subclasses to access them.

Simple parameterization is a good start. One of the pitfalls of using inheritance with this is if you try something like races and classes for dwarven warriors or elven wizards, you end up with DwarfWarrior, ElfWarrior, DwarfWizard and ElfWizard. All this effort writing out almost-identical code makes programming with Java seem staggeringly inefficient. It's even worse if you're doing player-controlled versions and computer-controlled versions. Lots of people do that and then think that inheritance is only useful in a few cases when nothing could be further from the truth.

You'll often hear the terms is-a and has-a with classes and inheritance. A Wizard is-a Player or an Archer is-a Player, or a WizardArcher is-a Wizard and is-a Archer (and by extent is-a Player). Inheritance describes is-a relationships. On the other hand, a player has-a equippedWeapon or has-a wornArmor. Fields in a class describe has-a relationships. However, we can also say that a Player has-a Job and has-a Race, and a Wizard is-a Job, Warrior is-a Job, and Elf is-a Race and Dwarf is-a Race. The two can even be simply concrete instances of one parent class using parameters if there's nothing majorly different between the two.
code:
// Early on in design we just change some numbers
Race ELF = new Race("Elf", 10,10,15,5);
Race DORF = new Race("Dwarf" 10,5,15,10);

// Later on we can split them into their own subclasses
Race ELF = new CookieBakingRace("Elf",10,10,15,5);
Race DORF = new ShortHairyRace("Dwarf",10,5,15,10);
Now if you call ELF.getBaseStrength(), you don't know if it's actually Race.getBaseStrength() or CookieBakingRace.getBaseStrength() but as long as both classes do the same thing, you won't notice the difference.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply