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?
Related
After getting the rest of it all working with samples, I tied to serialize my actual underlying object, and found that it would always kick back an error about not being able to guess about the class I'm trying to serialize. This is highly simplified example of what I'm trying to do, along with annotations that seem to make sense to me for how to do it.
I want to serialize a List<> of primitive (or boxed primitive) objects, in this case one int & one string. My actual class is all primitive (or boxed primitive) types also.
#JSONMapper
public static interface TestMapper extends ObjectMapper<TestElmt>{
TestMapper INSTANCE = new Webworkers_TestMapperImpl();
}
public static class TestElmt {
List<test> inerVar = new ArrayList<>();
public void addElement(test elmt){
inerVar.add(elmt);
}
public List<test> getElements(){
return inerVar;
}
}
#JSONMapper
public static class test{
public static test_MapperImpl MAPPER = new test_MapperImpl();
int x;
String y;
test(int X,String Y){
x = X;
y = Y;
}
}
But the error I get is:
Error:java: error while creating source file
java.lang.IllegalArgumentException: couldn't make a guess for
client.myEnclosingClass.test
The code in the question has two issues that will not allows it to compile :
First the test class should be named as Test - capital T - instead of test - small t -.
Second there should be a no args constructor on class test, otherwise the deserializers wont know how to create a new instance of the class, it will be generated but will have a compilation error in its create method.
if we change the test class like this all should work
#JSONMapper
public static class Test {
public static Test_MapperImpl MAPPER = new Test_MapperImpl();
int x;
String y;
public Test() {
}
Test(int X, String Y){
x = X;
y = Y;
}
}
this is because gwt-jackson-apt makes some assumptions and uses some conventions to generate the underlying serializers/deserializers.
suppose in Eclipse I have three packages with the following classes in each:
Packages: Classes
Head: head.java
Body: arms.java
Legs: feet.java
I want to define class info in brain.java and pass it through methods to the other classes (arms.java and feet.java) and update the contents of info.
class info {
// some vars such as bools,ints,strings
}
For example, have updateArms be a method defined in arms.java. I want to do the following in brain.java:
arms.updateArms( info );
I am having trouble finding how to first define a class that behaves this way, and secondly how to pass it as a parameter to another linked class.
First, you should learn about Java naming convention.
For example, package should be head, and the class should be Head.
Go back to your design: In OOP, we see the program as interactions between object instances.
In your example, it may look like:
class Arm {
void moveUp(SomeInfo info) {
...
}
}
class Brain {
private Arm leftArm;
private Arm rightArm;
void reachForward() {
rightArm.moveUp(...);
}
void connectLeftArm(Arm arm) {
this.leftArm = arm;
}
//....
}
class Body {
Brain brain;
Arm leftArm;
Arm rightArm;
public Body() {
this.brain = new Brain();
this.leftArm = new Arm();
this.rightArm = new Arm();
this.brain.connectLeftArm(this.leftArm);
this.brain.connectRightArm(this.rightArm);
}
}
I wish this demonstrate the difference of way of thinking.
If you start get used to the way OOP see things, then you can take next step in refining your design (e.g. by different design pattern)
You can achieve this using Inheritance.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
Sample Code helps you how to use the methods and properties of other classes.
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
this and super in java
I'm new to development. Something that I'm still unable to understand is the difference between this and super keywords. If there are any answers, it would be highly appreciated. Thanks.
this
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
super
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged).
super refers to the base class that the current class extends. this refers to the current class instance.
So, if Parent extends Child and you create a new Child(), super refers to the Parent class (and doing something like super() in the constructor would call the parent's constructor) and this refers to the actual Child instance you created with new.
Super refers to the superclass that a class extends. this refers to the current instance of a class.
These concepts can be confusing for new developers, they will be more clear when you learn about extending classes (inheritance). Sometimes when you refer to a variable or method, you might be being ambiguous for example if you repeated a class variable name in a method, the compiler won't know which variable you are referring to, so you can use this to specify you are referring to the current class's variable (not the local variable). The following would be ambiguous (and WRONG):
class Bike
{
int speed = 10;
public setSpeed(int speed)
{
speed = speed;
}
}
The compiler would have no idea what you intended, and will probably insult you with a cryptic (for a new developer) error message. Using this in the following way tells the compiler "I am referring to the class level variable, NOT the method level variable"
class Bike
{
int speed = 10;
//Constructors and shiz
public void setSpeed(int speed)
{
this.speed = speed;
}
}
(Although in practice you shouldn't duplicate variable names in this way!)
So to summarise, this tells the compiler that you're referring to the CURRENT class. Further ambiguity can arise when you extend classes (inherit functionality for a parent or super class), because the option of overriding the parent method arrises.
class Bike
{
public Bike()
{}
public void printSpeed()
{
System.out.println("This generic bike can go 10 m/s!!");
}
}
Now if we were to extend the bike class by introducing a more specific type of bike, we may want to override the printSpeed method to give the speed of our shiny new bike, like so:
class MountainBike extends Bike
{
public MountainBike() {}
public void printSpeed()
{
System.out.println("WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!");
}
public void printGenericSpeed()
{
super.printSpeed();
}
}
The super.printSpeed() tells the compiler to run this method from the parent class, so a call to super.printSpeed() would actually call the printSpeed() method in the Bike class. The following code:
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
mb.printGenericSpeed();
}
will print
WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!
This bike can go 10 m/s!!
Note that if we had not overridden the printSpeed() method, calling the following would be a call to the printSpeed() method of the Bike class.
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
}
would print
This bike can go 10 m/s!!
So to conclude, we use this to refer to the current class we're in, and super to refer to the parent of the class we're in.
In Java the keyword this refers to the current object of a class, like in:
class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
}
class Point3D extends Point {
public int z = 0;
public Point(int x, int y, int z) {
super(x,y);
this.z = z;
}
public String toString() {
return super.toString() + "," + z;
}
}
In the constructor of the class Point this.x refers to the x defined in the class, where x is the parameter passed into the constructor. Here this is used to resolve the ambiguity of the name x. The same thing is true for y.
In the class Point3D the method toString() uses the return value of the super class Point to produce its own return value.
this: is the reference to the current object in the methods of its class. Refer to any member of the current object through the this keyword.
super: is the derived class' parent when your class extends it through the extend keyword, and you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a protected fields.
this keyword refers to the current instance at that point in time.
super keyword refers to the parent/super class of the current class.
EX:
class Test
{
Test()
{
}
Test(int i)
{
System.out.println("i=" + i);
}
}
class Sample extends Test
{
int i;
void Sample(int i) //constructor
{
this.i=i; // referring class version of the i using 'this'
super(i); // passing parameter to Super/Parent class constructor.
}
}
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!
I'm new to Java and OOP,
I was using a private subclass (actually a struct) B in a class A, and everything went well until I decided to make a parent class C for subclass B. I want make public some of the protected members of class C.
For example:
public class A {
private class B extends C {
public int product;
public int x;
public int y;
public void add() {
product=x+y;
}
}
B b=new B;
b.x=1;
b.y=2;
b.multiply();
System.out.println(b.product+"="+b.x+"x"+b.y);
public class C {
protected int x;
protected int y;
public int sum;
public C(px,py) {
x=px;
y=py;
}
public void sum() {
sum=x+y;
}
}
And I get
Implicit super constructor C() is undefined for default constructor.
Must define an explicit constructor
Of course, I could remove extends C, and go back to what I had before. Or I could make a getter/setter. But I think it is understandable that an inner struct is acceptable, and it should be able to extend other classes.
The compiler message is reasonably clear - in B you've effectively got:
public B() {
super();
}
and that fails because there's no parameterless constructor in C to call. Either introduce a parameterless constructor, or provide an explicit constructor in B which calls the constructor in C with appropriate arguments.
I'm not sure it's a good idea to have all these non-private fields, mind you - nor is it a good idea for fields in B to hide fields in C. Do you really want an instance of B to have two x fields and two y fields? You realise they will be separate fields, don't you?
If you just want to effectively provide public access, you could have:
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
(and the same for y) and remove the extra fields from B. You can't change the actual accessibility of the fields in C though.
Okay, I was fuddling with my own code and found that the problem is I needed a protected default constructor for superclass C. It works now...