instantiating a class from array of interfaces - java

SEE THE EDIT HALFWAY DOWN THE POST.
I'm new to java and all the formal declarations of inheritance are getting me a little confused.
I have a interface like so:
public interface A{
public void one();
public void two();
}
and then I have two classes like so:
public class B implements A{
private int num;
public void one(){
...
}
public void two(){
...
}
public B(){
this.num = 1;
}
}
public class C extends B{
public C(){
super();
}
}
then I have a driver class like so:
public class Driver{
public static void main(String [] args){
A a_array[] = new A[5];
for(int i=0; i<6; i++){
if(i%2==0){
a_array[i] = new B();
}
else{
a_array[i] = new C();
}
}
}
}
Basically, given an array of interfaces I am trying to implement various classes that implement that interface.
Now my guess is there are several things wrong with this implementation, but I seem unable to sniff them out. Primarily right now I am getting the error 'B() is not abstract and does not implement method one()'.
EDIT:
alright lets try this...
the interface:
public interface Shape{
public double calcAread();
public double calcPerimeter();
}
the implementing class:
public class Rectangle implements Shape{
private double length;
private double width;
public double calcArea(){
return this.length*this.width;
}
public double calcPerimeter(){
return (this.length*2)+(this.width*2);
}
public Rectangle(double length, double width){
this.length=length;
this.width=width;
}
// then some other methods including the set methods
}
the extending class:
public class Square extends Rectangle{
public Square(){
super();
}
public Square(double sideLength){
super.setLength(sideLength);
super.setWidth(sideLength);
}
// some more methods
}
I can't think of very much more that would be useful other than to mention that there are other inheriting and extending classes off of these but they follow exactly the same design and sentax.
No errors when I compile shape, but the 'Rectangle is not abstract and does not override abstract method calcAread() in Shape' error is tripped when I compile the Rectangle class.
Hopefully this will be more enlightening.
Thanks

the only problem I see in the code is that the i<5 instead if i<6. array size is 5 and the initialization is set to i=0. (loop iterations should be 0,1,2,3,4, otherwise u will get ArrayIndexOutOfBound exception)
I compiled the code and its running fine.

What you've provided as example code will work just fine. My suspicion is that your exact code and your example code differ.
Without seeing the exact error message and B class it's hard to say, but I'm willing to bet you have either a return value or parameter difference between the definition of one in your interface and your one in your implementation.
Edit: Here's what I see as the problem. Your interface's method is called "calcAread". Is that d supposed to be on the end?
public double calcAread();
Because it's missing inside Rectangle
public double calcArea()
That's going to cause a problem. It makes me wonder how #Zohaib managed to compile it actually!

Related

In Java, can a class access the protected attribute in the super class of its super class?

For example,
public class Question {
protected String question, correctAnswer, type;
....
}
public class MultipleChoice extends Question{{
...
}
public class TrueFalse extends MultipleChoice{
public TrueFalse(){
this.type = "TrueFalse";
this.question = "Question is not assinged!";
this.correctAnswer = "Correct Answer is not assinged!";
}
....
}
It is clear that class MultipleChoice can access the question, type, and correctAnswer in class Question. But when I try to access them in class TrueFalse bythis.a. I got an error.
cannot be resolved or is not a field.
Thus, is the protected attribute in a class is only accessible in its subclass, but not sub-subclass? Three files are in the same package but different class file.
Yes it can. It's private methods that you can't access.
Well, I copy/pasted your code into an online compiler and tried it out. It worked, and you can find it here. That looks like a yes.
I mean, if those were private fields it would make sense, but with the rest there shouldn't be a problem (unless it is package-access only).
Are you declaring those classes in the same file? If one of those is a nested class, that might be the cause.
Reply to old version
Super-super field access, uh? Hmm...
How about ((A)this).a? If the field is protected, maybe this could work.
NOTE: If it still doesn't work for you, try using it inside a non-static method inside C.
public class MultilevelVar {
public static void main(String[] args) {
new C().fun();
}
}
class A {
protected int x = 10;
}
class B extends A {
int x = 20;
}
class C extends B {
int x = 30;
void fun() {
System.out.println(((A) this).x);
System.out.println(((B) this).x);
System.out.println(((C) this).x);
}
}

Creating a Generic for a Class

Assuming you have a class named Rational where each object contains two ints representing the numerator and the denominator, write the class definition line if you wanted to indicate that it would implement the generic interface Comparable and write the body of the required method with the signature:
public int compareTo(Object other);
so that it will only return -1 or 0 or +1 based on the relative order of the two objects based on the numerators and denominators.
I don't understand how to create a generic for Rational1, that takes the two integers (numer, denom). Any help with this, will be greatly appreciated. This is my Rational1 class so far:
public class Rational1 implements Comparable<Rational1> {
private int numer;
private int denom;
public Rational1(int numer,int denom){
this.numer = numer;
this.denom = denom;
}
public Rational1(Rational1 po){
po = new Rational1(numer, denom);
}
public int compareTo(Object other){
other = new Rational1(numer, denom);
if(numer>denom){
return 1;
}
else if(numer<denom){
return -1;
}
else{
return 0;
}
}
}
And this is my interface:
public interface Comparable<Rational1> {
public int compareTo(Object other);
}
And Lastly, my main which gives me an error on the last line when I call the generic:
public class Rational {
public static void main(String[] args){
Rational1 rational = new Rational1(4,3);
Comparable<Rational1> ration = new Comparable<Rational1>();
}
}
First things first, even if it is not direclty related with the question your constructor
public Rational1(Rational1 po) {
po = new Rational1(numer, denom);
}
is a complete nonsense. It should be
public Rational1(Rational1 po) {
this(po.numer, po.denom);
}
Your main method is also wrong, you have to provide a concrete class not an interface (an interface can never be instantiated) :
public static void main(String[] args){
Rational1 rational = new Rational1(4,3);
Comparable<Rational1> ration = new Rational1();
}
Finally, your implementation of the comparison is wrong because :
it's mathematically wrong
the signature of compareTo is not correct. It should be int compareTo(Rational1 that).
you are constructing a new instance instead of considering your parameter. It should be
#Override
public int compareTo(Rational1 that) {
return Integer.compare(numer*that.denom, that.numer*denom);
}
Always use #Override when implementing an abstract class/interface to make sure you are indeed overriding the abstract members.
Comparable<Rational1> is an interface. It has no constructor. You can't instantiate an instance of it. I assume this is the source of the error you are currently hitting, although you don't specify what the error is.
From the problem description (first paragraph), it's not clear what you are trying to do in main() at all. Your main goal is to write a definition for the compareTo() method, which you've done.
That said, the compareTo() method that you have written is nonsensical. You need to think (or read) more about what a rational number is and how you would go about comparing two rational numbers with one another.

what is use of referring object to an interface? [duplicate]

This question already has answers here:
What does it mean to program to an interface?
(17 answers)
Closed 9 years ago.
i have searched a lot but did not get exact answer for this Question hope i will get it from here.
what is exactly the use of referring object of a class to an interface instead of referring to the same class ??
void foo(list l){}
public static void main(String a[]){
List l = new ArrayList(); // why use this?
ArrayList a = new ArrayList(); //instead of this?
foo(l);
foo(a);
}
Maybe because an interface is something like a contract, which can be fullfilled by an implementation. You shouldn't depend on an implementation, because its about to change constantly, instead an interface/contract should not. Referring to an interface makes your implementation more robust.
Sometimes, the actual class of an instance does not matter, but only the interface it implements.
Also sometimes, it is impossible to know the actual class of an instance in compile time, but we only know the interface this class will implement.
For example, you have an interface called GeometricFigure
public static interface GeometricFigure {
public Double getGirth();
public String getName();
}
And you use this interface in a real class, for example, Canvas. Canvas has a list of GeometricFigures.
public class Canvas {
private List<GeometricFigure> figures;
public void printAllFigures() {
for (GeometricFigure figure : figures) {
System.out.println(figure.getName() + " " + figure.getGirth());
}
}
}
Now, your Canvas is independent of actual implementations of GeometricFigure. Canvas does not care how you is GeometricFigure is implemented, is it a square, circle or whatever. It only that this class can return a name and a girth so it can print them. So, the actual implementations can be Square, Circle, Triangle, etc. Only important thing is that these future classes implement the GemometricFigure interface.
For example:
public class Square implements GeometricFigure {
private String name;
private Double sideLength;
public Square(String name, Double sideLength) {
this.name = name;
this.sideLength = sideLength;
}
#Override
public Double getGirth() {
return 4 * sideLength;
}
#Override
public String getName() {
return name;
}
}

PolyMorphic class/Polymorphism/Inner Class -Getting error message

public class PolyMorphic {
public static void main(String[] args) {
PolyMorphic.printNumber(new IntNumber(1));
PolyMorphic.printNumber(new DoubleNumber(4.54));
}
public static void printNumber(MyNumber N) {
N.print(N);
System.out.println();
}
public abstract class MyNumber{
abstract void print(MyNumber N);
}
public class IntNumber extends MyNumber{
int x;
IntNumber(){
x = 3;
}
IntNumber(int x){
this.x = x;
}
void print(MyNumber N) {
double temp = (double)x;
System.out.printf("%.2f",temp);
}
}
public class DoubleNumber extends MyNumber{
double x;
DoubleNumber(){
x = 3.23;
}
DoubleNumber(double x){
this.x = x;
}
void print(MyNumber N) {
double temp = x;
System.out.printf("%.2f",temp);
}
}
}
So I am trying to create a method in the PolyMorphic class named printNumber which is polymorphic and can print(to the console) either an intNumber with two decimal places to the right or a DoubleNumber with three decimal places to the right. Such as PolyMorphic.printNumber(new IntNumber(1));
My Problem is this:
On the Lines:
PolyMorphic.printNumber(new IntNUmber(1));
PolyMorphic.printNumber(new DoubleNumber(4.54));
This is the error message:
" No enclosing instance of type PolyMorphic is accessible. Must
qualify the allocation with an enclosing instance of type PolyMorphic
(e.g. x.new A() where x is an instance of PolyMorphic)."
It gives me it for both instances and I am confused to as why It is not working. IF someone could just point me in the right direction I would be really appreciative.
Thank you.
Your inner classes require an instance of your PolymorphicClass because of the way you declared them. However, in your case, you don't need this, so you can mark your inner classes as static:
public static class IntNumber
and
public static class DoubleNumber
This is a Java design feature.
One other solution would be to operate on an instance of PolymorphicClass:
Polymorphic p = new Polymorphic();
p.printNumber(new IntNumber(1));
p.printNumber(new DoubleNumber(4.54));
EDIT:
You also need:
public static abstract class MyNumber
Don't nest your MyNumber class and its daughters inside of Polymorphic.
Nesting classes like that is only appropriate when the nested class (MyNumber, IntNumber, DoubleNumber) is part of the implementation of the enclosing class (Polymorphic). In your case, the only relationship between the two classes is that Polymorphic is calling methods on the Number classes.
By the way, the compiler has already told you one solution to your problem, if you would take the trouble to read and understand what it said. Be grateful, for few compilers are as obliging.
Edit - why is anyone downvoting a reply that is both correct and adds additional information to that provided by other answers?

Java overloading vs overriding

Hi I just want to make sure I have these concepts right. Overloading in java means that you can have a constructor or a method with different number of arguments or different data types. i.e
public void setValue(){
this.value = 0;
}
public void setValue(int v){
this.value = v;
}
How about this method? Would it still be considered overloading since it's returning a different data type?
public int setValue(){
return this.value;
}
Second question is: what is overriding
in java? Does it relate to inheritance. Let's I have the following:
public class Vehicle{
double basePrice = 20000;
//constructor defined
public double getPrice(){
return basePrice;
}
}
public class Truck extends Vehicle{
double truckPrice = 14000;
//constructor defined
public double getPrice(){
return truckPrice;
}
}
So now let's say I have the following
Truck truck = new Truck();
if I call
truck.super.getPrice()
this would return the price from the Vehicle class, 20,000
if I call
truck.getPrice()
this would return the price in the truck class, 14,000
Is my knowledge correct for both questions?
You are basically correct. Overloading is having multiple methods in a single class where the method has the same name. However, the return value is not seen as part of the signature of the method. Thus, you cannot overload a method by changing only the return value. You cannot have the following code, from your example:
public void setValue() {
this.value = 0;
}
public int setValue() {
return this.value;
}
This will fail to compile.
As Rob identified, I believe you mean overriding, and you have that correct. Note with overriding, you cannot change the return type. As of Java 5, you can return a derived type of what the base class method returned. Before Java 5, it must be the identical type. That is, you cannot do the below until Java 5 and later:
public class AnimalNoise {}
public class Miaw extends AnimalNoise {}
public class Animal {
public AnimalNoise makeNoise() {
return new AnimalNoise();
}
}
public class Cat extends Animal {
public Miaw makeNoise() {
return new Miaw ();
}
}
However, even in Java 5 and later, you cannot do the following:
public class Animal {
public String makeNoise() {
return "silence";
}
}
public class Cat extends Animal {
public Miaw makeNoise() {
return new Miaw ();
}
}
public class Miaw {}
Finally, a big difference between overloading and overriding that is often overlooked is that overloading is decided at compile time and overriding is decided at runtime. This catches many people by surprise when they expect overloading to be decided at runtime.
Correct; overloading is providing multiple signatures for the same method.
Overriding, which is what I think you mean by "overwriting" is the act of providing a different implementation of a method inherited from a base type, and is basically the point of polymorphism by inheritance, i.e.
public class Bicycle implements Vehicle {
public void drive() { ... }
}
public class Motorcycle extends Bicycle {
public void drive() {
// Do motorcycle-specific driving here, overriding Bicycle.drive()
// (we can still call the base method if it's useful to us here)
}
}
what you have described is correct.
For more clarification take a look at polymorphism concept. The Wikipedia has a good article
http://en.wikipedia.org/wiki/Polymorphism#Computing
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

Categories