Best way to make my prog more OOP friendly

  • (2 Pages)
  • +
  • 1
  • 2

29 Replies - 1610 Views - Last Post: 05 February 2013 - 10:38 AM Rate Topic: -----

#1 tmcraig  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-February 13

Best way to make my prog more OOP friendly

Posted 04 February 2013 - 02:02 AM

Hi Guys,

Im totally new to Java been leaning for last couple weeks. Im getting there but obviously loads to learn. I'm hoping this forum will be the place that helps me to grow.

So to the task at hand. Below is a simple program that works out the area of different shapes. I want to use OOP, i know i could seperate the shapes out, but the formulas are all differnt so wouldn inherate from just a general shape class would they?

Some people have mention interfaces or abstract classes, im still reading up on this. But how would you make this program more OOP friendly?

Thanks in advance.

Craig.

Code below.


Main class

package areaprog;

import java.util.Scanner;
import java.util.InputMismatchException;
public class Mainprog {


	public static void main (String [] args){
		
		//Area Menu Selection
		System.out.println("What shape do you need to know the area of?\n" +
		"1: Square?\n" +
		"2: Rectangle?\n" +
		"3: Triangle?\n" +
		"4: Circle? \n" +
		"5: Exit\n"		
		);
		
		//User input for menu

		Scanner reader = new Scanner(System.in);
		System.out.println("Number: ");
		
		//Menu syntax checking
		while (!reader.hasNextDouble())
		{
			System.out.println("Thats not a number you tool.\n");
			System.out.println("Now pick again\n" +
					"1: Square?\n" +
					"2: Rectangle?\n" +
					"3: Triangle?\n" +
					"4: Circle? \n" +
					"5: Exit\n"		
					);
		
			reader.next(); //ask for next token		
	    }				
			double input = reader.nextDouble();
			reader.nextLine();
		
	
		
		//Depending on user selection, depends on what method is called using switch.
	Scanner scan = new Scanner(System.in);

		//Square selection and InputMismatch Exception
	
	try {
	
		if (input == 1){
		    System.out.println("What is a length of 1 side of the Square?\n");
		    	double s1 = scan.nextDouble();
				double SqAns = AreaCalculator.getSquareArea(s1);
				System.out.println("The area of you square is: " + SqAns);
		    
		     		   }	
		}   		
	catch (InputMismatchException e)
	   {
		System.out.println("Why are you trying to be clever? use an interger");
		
		
	   }
	
		//Rectangle selection    
		    if (input == 2){
			System.out.println("What is the width of your rectangle?.\n");
		        double r1 = scan.nextDouble();
		    System.out.println("What is the height of your rectangle?\n");
		        double r2 = scan.nextDouble();
		        double RecAns = AreaCalculator.getRectArea(r1, r2);
		    System.out.println("The area of your rectangle is: " + RecAns);    
		    }
		//Triangle selection
		if (input == 3){
			System.out.println("What is the base length of the triangle?.");
				double t1 = scan.nextDouble();
			System.out.println("What is the height of your triangle?");
				double t2 = scan.nextDouble();
				double TriAns = AreaCalculator.getTriArea(t1, t2);
			System.out.println("The area of your triangle is " + TriAns);
		}
		//Circle selection
		if (input == 4){
			System.out.println("What is the radius of your circle?.");
			    double c1 = scan.nextDouble();
			    double CircAns = AreaCalculator.getCircleArea(c1);
			System.out.println("The area of your circle is " + CircAns);    
			
		}
		//Exit application
		if (input == 5){
			System.out.println("Goodbye.");
		
		}
				
	
	}
		
}








Formula code


package areaprog;


public class AreaCalculator {
	
	public static double getRectArea(double width, double height) {
		double aValue = width * height;
		
		return aValue;
		
		
	}
	
	public static double getCircleArea(double radius){
		double PI = Math.PI;
		double aValue = PI * Math.pow(radius, 2);
		
		return aValue;
		
		
	}

	public static double getSquareArea(double side) {
		double aValue = Math.pow(side, 2);
		
		return aValue;
		
		
	}
	
	public static double getTriArea(double base , double height) {
		double aValue = (base/2)* height;
		
		return aValue;
		
		
	}
}




Is This A Good Question/Topic? 0
  • +

Replies To: Best way to make my prog more OOP friendly

#2 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 03:51 AM

I am by no means an expert in Java but my first attempt would be the following, using an Interface:

public class NewMain {

    public static void main(String args[]) {

        Square mySquare = new Square(10.0);
        Rectangle myRect = new Rectangle(3.0, 4.0);
        
        System.out.printf("%.2f\n", mySquare.Area());
        System.out.printf("%.2f\n", myRect.Area());
        
        System.exit(0);
    }
}

interface IShape {
    public double Area();
}

class Square implements IShape {
    private double _side;
    
    public Square(double side) {
        _side = side;
    }
    public double Area() {
        return _side * _side;
    }
}

class Rectangle implements IShape {
    private double _width, _height;
    
    public Rectangle(double width, double height) {
        _width = width;
        _height = height;
    }
    public double Area() {
        return _width * _height;
    }
}

Someone will probably come along and correct or improve my code :)
Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 04:11 AM

An interface promises common behaviour of different classes. It allows us to loop through all class-instances that implement the interface:

        ArrayList<IShape> shapes = new ArrayList<>();
        
        Square mySquare = new Square(10.0);
        shapes.add(mySquare);
        Rectangle myRect = new Rectangle(3.0, 4.0);
        shapes.add(myRect);
        //Circle myCirc = new Circle(5.0); // create the class definition first
        //shapes.add(myCirc);
        
        System.out.printf("Square has area %.2f\n", mySquare.Area());
        System.out.printf("Rectangle has area %.2f\n", myRect.Area());
        //System.out.printf("Circle has area %.2f\n", myCirc.Area());
        
        for (IShape aShape : shapes) {
            System.out.printf("Shape has area %.2f\n", aShape.Area());
        }

This post has been edited by andrewsw: 04 February 2013 - 04:12 AM

Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5901
  • View blog
  • Posts: 12,805
  • Joined: 16-October 07

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 06:03 AM

First, for now, only use "static" in "public static main..." Static and OOP tend to be at odds.

I agree with interfaces, but let's forget them for the moment.

You have a base object, called Shape. You know you want shape to have a method called getArea. Since different shapes can require different parameters, you'll want to figure what they are.

Let's define the basic things a Shape might have:
class Shape {
	public String getName() { return "Shape"; }
	public double getArea() { return 0; } // we don't really have an area for this; yet
}



So, what properties does your Square have?
class Square extends Shape {
	private final double side; // this is the one property of the Square
	public Square(double side) { this.side = side; } // we load it in the constructor
	// we "override" our base class
	public String getName() { return "Square"; }
	public double getArea() { return this.side * this.side; }
}



In your main:
private Shape getShapeFromUser(int choice) {
	if (choice == 1){
		System.out.println("What is a length of 1 side of the Square?\n");
		double side = reader.nextDouble();
		return new Square(side);
	} else if (choice == 2) {
		// ...
}

// ...
System.out.println("The area of your " + shape.getName() + " is: " + shape.getArea());



In OOP, you want to understand classes, then base classes, then abstract classes, then interfaces. Then you'll ask why the hell use an abstract class vs. an interface. Once you get that, you're pretty much there.

Shape could be an interface. It should otherwise be abstract. However, for the moment, it's good OO to just learn classes.

Hope this helps.

This post has been edited by baavgai: 04 February 2013 - 06:03 AM

Was This Post Helpful? 4
  • +
  • -

#5 tmcraig  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-February 13

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 06:25 AM

@baavgai, that's exactly what i needed fella. As i'm new breaking down like that is spot on :)

I will be taking on board what you said about learning classes first then base classes.

I'll change my program and post back once I've got it running as i need to.

All ready like this forum over any others I've visited.

Thanks to both of you :)

Craig
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 07:05 AM

Sorry, I skipped a bit!

@OP Please! don't let the following point distract you from your studies :)

The issue I have with all introductory texts on OOP is that they always start with classical inheritance (aka implementation inheritance). But this is rarely used in the real world; it's all about interfaces and, less often, abstract classes, and combinations of these.

All the examples used in introductory texts are misleading :rolleyes:/>. A typical example would be an Animal and then Cat, Dog. The issue I have is that it should not be possible to instantiate an Animal. No such creature exists?! Similarly for Person, Shape. If it is a Bank example, with Customer, etc., then there is no such entity as Person; a Person only exists if they are a Customer (as far as the Bank is concerned).

Anyway, sorry to sidetrack. Andy.

This post has been edited by andrewsw: 04 February 2013 - 07:07 AM

Was This Post Helpful? 0
  • +
  • -

#7 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7950
  • View blog
  • Posts: 13,543
  • Joined: 19-March 11

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 08:23 AM

View Postandrewsw, on 04 February 2013 - 05:51 AM, said:

Someone will probably come along and correct or improve my code

One trivial improvement would be to observe naming conventions - in java, we use this.fieldName, not _fieldName. :)/>/>
Also, what's an "IShape"? Is that Hungarian for Shape?


A little less nitpicky:

class Square extends Rectangle {
    public Square(double side) {
        super (side, side);
    }
}



This is preferable because it leverages the actual relationship that we're trying to model. Now, anything we know about Rectangles, we know about Squares, for free.

This post has been edited by jon.kiparsky: 04 February 2013 - 08:24 AM

Was This Post Helpful? 2
  • +
  • -

#8 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 08:38 AM

Criticising my underscore! You Java people.. :rolleyes:. I was planning to convert them to properties anyway - once I work out how!

IShape is Scottish; as in, "Aye, Shape".

As a challenge, could a sphere extend a circle? That is, constructing a topology.

What is the commented line achieving please, which I came across?

interface IShape {
    String mybase = "shape";        // what is this??
    public double Area();
}


[I'm sticking with I for the moment..]
Was This Post Helpful? 1
  • +
  • -

#9 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7950
  • View blog
  • Posts: 13,543
  • Joined: 19-March 11

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 08:54 AM

View Postandrewsw, on 04 February 2013 - 10:35 AM, said:

As a challenge, could a sphere extend a circle? That is, constructing a topology.


Interesting question. Are you thinking

public class Sphere implements Solid extends Circle


and by analogy

public class Block implements Solid extends Rectangle


But then we get into trouble:

public class Cube implements Solid extends ?Square?


This looks questionable: the more obvious hierarchy would have Cube extending Block, as Square extends Rectangle.
And here we might be tempted to cast a covetous eye at Scala and its Traits, but maybe there's something we can do with the Java model. Might have to think about that a little.
Was This Post Helpful? 0
  • +
  • -

#10 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1413
  • View blog
  • Posts: 3,133
  • Joined: 05-April 11

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:00 AM

Sorry for teasing you jon, but you are doing implements before extends which is not allowed
public class Sphere extends Circle implements Solid


I just wanted to contributed something to the conversation :innocent:
Was This Post Helpful? 1
  • +
  • -

#11 tmcraig  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-February 13

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:01 AM

With regards to IShape i read somewhere or saw a video adding the I before the word show people reading it that its an interface. But the word interface before that gives it away ;)

Craig
Was This Post Helpful? 0
  • +
  • -

#12 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7950
  • View blog
  • Posts: 13,543
  • Joined: 19-March 11

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:03 AM

I suppose after twitting andrewsw for his underscore, I deserve a dose of my own medicine. :)
Was This Post Helpful? 0
  • +
  • -

#13 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7950
  • View blog
  • Posts: 13,543
  • Joined: 19-March 11

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:12 AM

View Posttmcraig, on 04 February 2013 - 11:01 AM, said:

With regards to IShape i read somewhere or saw a video adding the I before the word show people reading it that its an interface. But the word interface before that gives it away ;)/>



Yep. Hungarian notation is fine, I guess, in some languages, but in Java you always know the types of your objects, so it's just noise. I find it actually makes things a lot harder to read, personally.
Was This Post Helpful? 0
  • +
  • -

#14 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:15 AM

View Posttmcraig, on 04 February 2013 - 09:01 AM, said:

With regards to IShape i read somewhere or saw a video adding the I before the word show people reading it that its an interface. But the word interface before that gives it away ;)/>

Craig

The word interface only occurs in the definition, not when Shape is used elsewhere.

In other languages (C#, VB.NET) it is the convention to start interfaces with a capital I, but Java-nistas don't do this. (They're supposed to know what's going on :) Added: just read Jon's comment.. )

View Postjon.kiparsky, on 04 February 2013 - 09:12 AM, said:

Yep. Hungarian notation is fine, I guess, in some languages, but in Java you always know the types of your objects, so it's just noise. I find it actually makes things a lot harder to read, personally.

This is the practice in .NET, but .NET doesn't use Hungarian notation; this is an accepted exception.

This post has been edited by andrewsw: 04 February 2013 - 09:16 AM

Was This Post Helpful? 0
  • +
  • -

#15 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Re: Best way to make my prog more OOP friendly

Posted 04 February 2013 - 09:23 AM

@jon

I'll have to gen up on topology a little/lot, but I was thinking of a more formal class structure - to represent 1st, 2nd order, etc., elements/groups (I need to find the correct terminology..!), and then to have square, circle etc., extend these groups.

Added: Oh, and I prefer interfaces as it shouldn't be possible to instantiate a Shape (or Group) :) (as I suggested earler).

This post has been edited by andrewsw: 04 February 2013 - 09:54 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2