android Override a function in subclass - java

I make a class Figure then two subclasses from it. Figure super class have a method named are(). this is the all class.
public class Figure
{
public double a, b;
public Figure(double a,double b) {
this.a = a;
this.b = b;
}
public double are() {
return 0;
}
}
public class Rectangle extends Figure
{
Rectangle(double a, double b) {
super(a,b);
}
double area (){
return this.a*this.b;
}
}
class Triangle extends Figure
{
Triangle(double a, double b) {
super(a,b);
}
// override area for right triangle
double area () {
return a * b / 2;
}
}
to easy print outpute I make
public void toastM(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
now I use this code
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
toastM("are..... " + figref.are());
figref = t;
toastM("are..... " + figref.are());
figref = f;
toastM("are..... " + figref.are());
expected values are 45 40 0
but it come 0 0 0

The parent class has a method called
double are()
the child classes
double area()
so it's not overridden

The functions you are overriding in both Rectangle and Triangle are called area AND NOT are as in the Figure class

You are calling the are() function of the super class Figure, not the area() function the subclass.

Related

Quadratic Formula solution issue

I need some help with a program that i am trying to create. This is a Quadratic Equation Formula, where i have 2 classes.
The only issue that i am getting is code
"QuadraticEquation Equation = new QuadraticEquation(a, b, c);"
I am getting the error that says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type TestQuadraticEquation is accessible. Must qualify the allocation with an enclosing instance of type TestQuadraticEquation (e.g. x.new A() where x is an instance of TestQuadraticEquation).
at TestQuadraticEquation.main(TestQuadraticEquation.java:12)
This error is occurs at line 12 (code above) and i need to find out what is wrong with that section.
public class TestQuadraticEquation
{
public static void main (String [] args)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Please enter the coefficients a, b and c in the order: ");
double a = scan.nextDouble();
double b = scan.nextDouble();
double c = scan.nextDouble();
QuadraticEquation Equation = new QuadraticEquation(a, b, c);
if (Equation.getDiscriminant() > 0)
{
System.out.println("The roots of the equations are " + Equation.getRoot1()
+ " and " + Equation.getRoot2());
}
else
{
System.out.println("The equation has no roots.");
}
}
class QuadraticEquation
{
private double a;
private double b;
private double c;
QuadraticEquation()
{
a = 0;
b = 0;
c = 0;
}
QuadraticEquation (double newA, double newB, double newC)
{
a = newA;
b = newB;
c = newC;
}
public double getA()
{
return a;
}
public double getB()
{
return b;
}
public double getC ()
{
return c;
}
public double getDiscriminant()
{
return (Math.pow(b,2) - 4 * a * c);
}
public double getRoot1()
{
return ((-b + Math.sqrt(getDiscriminant())/(2 * a)));
}
public double getRoot2()
{
return ((-b - Math.sqrt(getDiscriminant())/(2 * a)));
}
}
}
Here you are trying to create an instance of inner class which is QuadraticEquation class. QuadraticEquation class lies inside TestQuadraticEquation so, in order to create instance you can either declare your QuadraticEquation as static class please refer to the link: problem creating object of inner class in java
Other choice is to seperate the class such that QuadraticEquation.java and move the code of QuadraticEquation class there. That way it is no longer inner class.
Also, the other choice would be like the compiler suggested you create instance of TestQuadraticEquation and then from there you can create new object of QuadraticEquation which can be done by:
QuadraticEquation Equation = new TestQuadraticEquation(). new QuadraticEquation(a, b, c);

Difference between Static and Non-Static methods/Subroutines

I was reading a java book, where I came across this statement:
So, every subroutine is contained either in a class or in an object
I'm really confused why does it say "class or in an object"
I would like some explanation.
Let's try this example
public class Demo {
public static void classMethod() {
System.out.println("Call to static method");
}
public void objectMethod() {
System.out.println("Call to object method");
}
public static void main(String[] args) {
Demo demo = null;
demo.classMethod();
//demo.objectMethod();// throws NPE if uncommented
}
}
This code will work (even if the demo variable is null) because static method classMethod is contained within the class Demo. The commented line will throw a NullPointerException because the method objectMethod is not contained in the class but in the object so will need an instance of Demo class to call it.
Subroutine is a method written inside a class. We use them to do various tasks. That statement states that these methods/subroutines are written in an object or a class.
If we have an object instantiated, it will create new methods for every non-static method for that object which were defined in the class of the object. Hence those non-static methods/subroutines are in the object.
But if the class is a static class, we can't have any objects from it. But we can use subroutines/methods of that class. So, they are in a Class
That's what your statement says.
EDIT:
I thought to give an example for this.
public class ExampleClass {
public String getNonStaticString() {
return "This String is From Non-Static Method";
}
public static String getStaticString() {
return "This String is From Static Method"
}
}
Then, if you need to get the static String, all you have to do is
String staticString = ExampleClass.getStaticString();
Note that I havn't created an object from the ExampleClass Here. I just used the method.
But, if you need to get the String from the non-static method, you should instantiate an object first.
ExampleClass exampleObject = new ExampleClass();
String nonStaticString = exampleObject.getNonStaticString();
static methods also known as class method. Static method associated only with the class and not with any specific instance of that class(object).
So, every subroutine is contained either in a class or in an object
The statement is technically not 100% correct.
First of all, subroutines in java are commonly called methods. The following two terms are often used interchangeably:
Method: A subroutine working with an object instance, this.
Function: A subroutine not working with an object instance.
Here is an example scenario which should you get an idea what that means:
public class Circle {
//region static code
//we cannot call "this" in a static context, main(String[]) is no exception here
public static void main(String[] args) {
Circle a = new Circle(0, 0, 10);
Circle b = new Circle(10, 10, 2);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("circumference of a = " + a.getCircumference());
System.out.println("circumference of b = " + b.getCircumference());
System.out.println("area of a = " + a.getArea());
System.out.println("area of b = " + b.getArea());
System.out.println("distance of a, b = " + distance(a, b));
System.out.println("a, b intersect = " + (intersects(a, b) ? "yes" : "no"));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to calculate their distance
public static double distance(Circle a, Circle b) {
return Math.sqrt(squared(a.x - b.x) + squared(a.y - b.y));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to check for an intersection
public static boolean intersects(Circle a, Circle b) {
return a.radius + b.radius > distance(a, b);
}
//we cannot call "this" in a static context, but we have the number x as parameter we can use to calculate the square of
public static double squared(double x) {
return x * x;
}
//we cannot call "this" in a static context, but we have the number radius as parameter we can use to check if its value is in range
public static void checkRadius(double radius) {
if(radius < 0) {
throw new IllegalArgumentException("radius must be >= 0");
}
}
//endregion
//region member / instance code
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
checkRadius(radius);
this.x = x;
this.y = y;
this.radius = radius;
}
//region getters and setters
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getX() {
return x;
}
//we may refer to the instance variables with or without "this", but in this case we have two variables with name "x"
//if we write "x", the parameter is taken. for the circle's x coordinate, we need to clarify with "this.x"
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
checkRadius(radius);
this.radius = radius;
}
//endregion
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * squared(radius);
}
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
#Override
public String toString() {
return "circle at [" + x + ", " + y + "] with radius " + radius;
}
//endregion
}
Output:
a = circle at [0.0, 0.0] with radius 10.0
b = circle at [10.0, 10.0] with radius 2.0
circumference of a = 62.83185307179586
circumference of b = 12.566370614359172
area of a = 314.1592653589793
area of b = 12.566370614359172
distance of a, b = 14.142135623730951
a, b intersect = no

Why wont my code run? Java program to add numbers

Can you help me find my error?
I'm trying to use these two methods here but my output is not working.
class Nine {
public static void Nine(String[] args) {
int x,y,z;
y = 3;
x = 7;
z = addEm(a, b);
System.out.println("answer= " +x);
}
public static addEm (double a, double b){
int c;
c = a+b;
}
}
Actually there are a lot of error in your code:
z=addEm(a, b);
here a and b are meaningless, you should use z=addEm(y,x); (if your intent is to sum three with seven)
System.out.println("answer= " +x);
I guess that you want to show the the results of the sum, therefore you should print z (and not x), so you should substitute with System.out.println("answer= " +z);
public static addEm (double a, double b) {
Here you missed the return type, and you need to consider also the type of parameters a and b. Since y,x and z are int, it is better if also a and b are int, and therefore specify also the return type as int:
public static int addEm (int a, int b) {
Or you can declare everything (y,x,z,a,b and return type) as a double: the important here is that they should be all of the same type. Moreover you miss also the return statement of the function addEm, that summarizing becomes:
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
And finally also the function
public static void Nine(String[] args)
it is not right named for an entry point: its names should be main.
So in conclusion, if you apply all the fix (by modifying as less as possible your original code) a code that compile, run and works following some 'logic' is:
class Nine {
public static void main(String[] args) {
int x, y, z;
y = 3;
x = 7;
z = addEm(y, x);
System.out.println("answer= " + z);
}
public static int addEm(int a, int b) {
int c;
c = a + b;
return (c);
}
}
Man, this is a very basic java lesson:
every prog need an entry point, which is in java:
public static void main(String args[]){}
And then your code will execute.
You're passing arguments a and b to addEm, but those variables aren't initialized. I'm expecting you wanted to pass x and y instead.
class Nine
{
public static void Nine(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " +x);
}
public static addEm (double a, double b)
{
int c;
c=a+b;
}
}
Your code will not work because your addEm method does not have any return type. In addition, the method you wrote takes Double params but while using you are trying to pass int to it. You also do not have any main method. I am assuming you misspelled or misunderstood the main method so below is the code which should work
class Nine
{
public static void Main(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " + x);
}
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
}

Using an ArrayList to output perimeters of triangles

I'm trying to write a program that takes in the different sides of a triangle, error-checks to make sure they would be valid, and then outputs them using an ArrayList.
I want it to look something like this...
"Perimeter of triangle t1 is 24."
"Perimeter of triangle t2 is 30"
The ArrayList is my main issue here, I think (probably have more issues). Below, I just tried my best to implement the ArrayList, but obviously couldn't get it. Also, how would I write/change my toString function, so that it would also contain the name of the object created in main (i.e. t1, t2, etc.)?
Thanks for looking!
import java.util.*;
public class Tri {
public static void main(String []args){
Triangle t1 = new Triangle(7, 5, 4);
Triangle t2 = new Triangle(9, 6, 1);
System.out.println(t1.perimeter());
System.out.println(t2.perimeter());
ArrayList<Triangle>allTriangles = new ArrayList<Triangle>();
}
public static double totalPerimeter( ArrayList<Triangle>a ){
System.out.println(Arrays.toString( a.toArray()));
for( int i = 0; i < a.length; i++){
System.out.println( a.perimeter[i]);
}
}
class Triangle{
public Triangle( double a, double b, double c ){
this.sideA = a;
this.sideB = b;
this.sideB = c;
if (checkSides() == true){}
}
public double getA(){
return sideA;
}
public double getB(){
return sideB;
}
public double getC(){
return sideC;
}
public Triangle setA( double a ){
sideA = a;
return this;
}
public Triangle setB( double b ){
sideB = b;
return this;
}
public Triangle setC( double c ){
sideC = c;
return this;
}
public String toString(){
return "Perimeter of triangle is " + perimeter;
}
public double perimeter(){
if (checkSides() == true)
perimeter = (sideA+sideB+sideC);
return perimeter;
}
private boolean checkSides(){
if (!(sideA+sideB>sideC) && (sideA+sideC>sideB) && (sideB+sideC>sideA)){
die("Not valid sides of triangle.");
return false;
}
else return true;
}
public void die( String msg ){
System.err.println( "\nFatal error: " + msg );
System.exit( 1 );
}
private double perimeter;
private double sideA;
private double sideB;
private double sideC;
}
Here is what your code should be:
import java.util.*;
public class Tri {
public static void main(String []args){
Triangle t1 = new Triangle(7, 5, 4);
Triangle t2 = new Triangle(9, 6, 1);
System.out.println(t1.perimeter());
System.out.println(t2.perimeter());
ArrayList<Triangle>allTriangles = new ArrayList<Triangle>();
allTriangles.add(t1);
allTriangles.add(t2);
System.out.println(totalPerimeter(allTriangles));
}
public static double totalPerimeter( ArrayList<Triangle>a ){
double tp = 0.0;
for(Triangle t : a) {
System.out.println( "peri : " + t.perimeter());
tp += t.perimeter();
}
return tp;
// for( int i = 0; i < a.length; i++){
//
// System.out.println( a.perimeter[i]);
//
// }
}
static class Triangle{
public Triangle( double a, double b, double c ){
this.sideA = a;
this.sideB = b;
this.sideB = c;
if (checkSides() == true){}
}
public double getA(){
return sideA;
}
public double getB(){
return sideB;
}
public double getC(){
return sideC;
}
public Triangle setA( double a ){
sideA = a;
return this;
}
public Triangle setB( double b ){
sideB = b;
return this;
}
public Triangle setC( double c ){
sideC = c;
return this;
}
public String toString(){
return "Perimeter of triangle is " + perimeter;
}
public double perimeter(){
if (checkSides() == true)
perimeter = (sideA+sideB+sideC);
return perimeter;
}
private boolean checkSides(){
if (!(sideA+sideB>sideC) && (sideA+sideC>sideB) && (sideB+sideC>sideA)){
die("Not valid sides of triangle.");
return false;
}
else return true;
}
public void die( String msg ){
System.err.println( "\nFatal error: " + msg );
System.exit( 1 );
}
private double perimeter;
private double sideA;
private double sideB;
private double sideC;
}
}
In your totalPerimeter function:
Since a is of type ArrayList, it doesn't have a length attribute. It does however have a size() method. Reference: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html.
Since a is of type ArrayList, it does not have a perimeter array field. Did you perhaps mean something like a.get(i).perimeter()?
First Question:
The ArrayList is my main issue here, I think (probably have more
issues). Below, I just tried my best to implement the ArrayList, but
obviously couldn't get it.
Well, it seems you are missing the return statement and have a logical issue in your totalPerimeter(...) method. You need to make sure to add the total perimeter up in a variable, then return that variable. Also, ArrayList use the method size() for length of the list instead of length. Also, you access ArrayList objects using the get(...) method.
public static double totalPerimeter( ArrayList<Triangle>a ){
double total = 0.0; //give default value of 0
for( int i = 0; i < a.size(); i++){
total = total + a.get(i).perimeter(); //add up total
}
return total;//return it back!
}
Second Question:
Also, how would I write/change my toString function, so that it would
also contain the name of the object created in main (i.e. t1, t2,
etc.)?
I don't think you can do that. However, you could pass a String to the constructor:
private String name;
public Triangle( double a, double b, double c, String variableName){
this.sideA = a;
this.sideB = b;
this.sideB = c;
this.name = variableName;
if (checkSides() == true){}
}
Then in your main:
Triangle t1 = new Triangle(7, 5, 4, "t1");
Triangle t2 = new Triangle(9, 6, 1, "t2");
You can then update your toString(...) method and access the variable name.
Note: Final thing to note is that when you checkSides() and it returns false. You should throw an Exception or give the user a warning (ex. print out "WARNING: invalid sides").

Calling a method with parameters within another method located in a superclass

I was wondering how I could call getJD() within getToD and keep the parameters intact,(or temporarily set the parameters as variables in main and call the variables to the method).
The parameters are going to be input using the scanner class later in the main method.
import static java.lang.Math.*;
public class jdMethods
{
public static double getJD(double y, double m, double d){
if (m<=2.0){
y--;
m += 12.0;
}
double a=floor(y/100.0);
return (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
}
public static double getToD(int h, int m, int s)
{
double a = getJD(a, a, a) + ((h-12)/24) + (m/1440) + (s/86400);
return a;
}
}
Edited for clarity.
It's not perfectly clear on what you are trying to do, but I assumed that you just want to save the result of your first getJD() and to use the result within your getToD(), so I made a private _jd and created a setter and getter for it.
import static java.lang.Math.*;
public class jdMethods
{
private double _jd;
public double getJD(){
return _jd;
}
public void setJD(double y, double m, double d){
if (m<=2.0){
y--;
m += 12.0;
}
double a=floor(y/100.0);
_jd = (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
}
public double getToD(int h, int m, int s)
{
double a = getJD() + ((h-12)/24) + (m/1440) + (s/86400);
return a;
}
}
So here is how you call it:
jdMethods testRun = new jdMethods();
testRun.setJD(1,2,3);
System.out.println(testRun.getToD(3, 2, 1));
All those parameters will be intact since you are using double and int, those are not Object s so it's value is copied when passed to a function, unlike Object s that a reference to it is passed to the function.
About your code, undefined variable a won't let it compile:
double a = getJD( a, a, a ) + ((h-12)/24) + (m/1440) + (s/86400);
I don't get what you are trying to do there, remember that a from getJD method is not the same a into getToD.

Categories

Resources