I have an abstract class like this
public abstract class Temperature
{
private float value;
public Temperature(float v)
{
value = v;
}
public final float getValue()
{
return value;
}
public abstract Temperature toCelsius();
public abstract Temperature toFahrenheit();
public abstract Temperature toKelvin();
}
then I have classes that extend this Temperature class, example:
public class Celsius extends Temperature
{
public Celsius(float t)
{
super(t);
}
public String toString()
{
return "";
}
#Override
public Temperature toCelsius() {
// TODO Auto-generated method stub
return this;
}
public Temperature toKelvin(){
return new Kelvin(this.getValue() + 273);
}
#Override
public Temperature toFahrenheit() {
// TODO Auto-generated method stub
return new Fahrenheit(this.getValue() * 9 / 5 +32);
}
}
main method creates objects of of Celcius
Temperature inputTemp = null, outputTemp = null;
inputTemp = new Celsius(temp_val);
outputTemp = inputTemp.toCelsius();
then prints the object by calling this method
System.out.println("\n The converted temperature is " + outputTemp.toString() +"\n\n");
}
What do i have to put in the toString method in order to print the desired value? this.super.getValue() didnt work and im kinda clueless. Since we are not going to be returning the same object everytime, dont we have to use the superclass?
It will be enough if you use:
public String toString()
{
return Float.toString(this.getValue());
}
this.super is invalid syntax. super is not a field of this. It's a keyword that allows calling the superclass implementation of a method rather than calling the overridden implementation, from the current class. You just need
return Float.toString(this.getValue());
or
return Float.toString(getValue());
or even
return Float.toString(super.getValue());
But using super.getValue() is useless, since the subclass doesn't override the base getValue() method, and you thus don't need to explicitely use the super implementation of the method.
Related
I'm looking for a way to convert a long or Long to a type derived from Number:
public class IdentityConverter<ConvertedT extends Number> implements IBitcodeConverter<ConvertedT> {
public IdentityConverter() {
}
#Override
public ConvertedT FromBitcode(Long theBitcodeVal) {
return new ConvertedT(theBitcodeVal.longValue());
}
#Override
public Long ToBitcode(ConvertedT theConvertedVal) {
// TODO Auto-generated method stub
return theConvertedVal.longValue();
}
}
The Problem is the FromBitcode method. The current code doesn't work. How do I get a ConvertedT which is a Number from a Long? Surely there is a simple way to do that...
new ConvertedT won't work because ConvertedT is a type variable.
You need to provide something like a Function<Long, ConvertedT> (or a LongFunction<ConvertedT>) to the constructor of IdentityConverter, in order to be able to construct the right kind of thing.
public class IdentityConverter<ConvertedT extends Number> implements IBitcodeConverter<ConvertedT> {
private final Function<Long, ConvertedT> fn;
public IdentityConverter(Function<Long, ConvertedT> fn) {
this.fn = fn;
}
#Override
public ConvertedT FromBitcode(Long theBitcodeVal) {
return fn.apply(theBitcodeVal);
}
// ...
}
I have a task to:
Modify the class Car so that it overrides the method setCapacity with its own version which output the message "Cannot change capacity of a car" and does not change the engine capacity.
I attempted to solve the task which the code below, but it keeps on using the Vehicle class's setCapacity method instead of the Car method.
class Vehicle // base class
{
int capacity;
String make;
Vehicle(int theCapacity, String theMake)
{
capacity = theCapacity;
make = theMake;
}
void print()
{
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
System.out.println("New capacity = " + capacity);
}
}
class Car extends Vehicle
{
String type, model;
Car(int theCapacity, String theMake, String theType, String theModel)
{
super(theCapacity, theMake);
type = theType;
model = theModel;
}
public void print()
{
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
public void setCapacity()
{
System.out.println("Cannot change capacity of a car");
}
}
class Task3
{
public static void main(String[] args)
{
Car car1 = new Car(1200,"Holden","sedan","Barina");
Vehicle v1 = new Vehicle(1500,"Mazda");
v1.setCapacity(1600);
v1.print();
car1.setCapacity(1600);
car1.print();
}
}
Your setCapacity() method of the Car class doesn't override the setCapacity(int newCapacity) method of the Vehicle class.
In order to override a method of the base class, the sub-class method must have the same signature.
Change
public void setCapacity()
{
System.out.println("Cannot change capacity of a car");
}
to
#Override
public void setCapacity(int newCapacity)
{
System.out.println("Cannot change capacity of a car");
}
Note that adding the #Override attribute is optional, but it will tell the compiler that you intended to override a base-class method (or implement an interface method), which will lead to a helpful compilation error if you declared the overriding method incorrectly.
The problem may be that the class Car's method whose name is "setCapacity", it is not override its parent class Vehicle's method with the same name.Because it has not a param, but there is a param in its parent class.
Hope can help you!
I've got a small question because oft a topic I didn't understand. There is one variable in a class. In the first method I want to give her a value. The second method have to change the value of this variable again. The new value of the variable is needed by a third method. I want to change and use this variable on every point of the class. Is this possible? I hope you know what I mean. Thanks for every help!
It is possible.
public class Test{
int counter;
public void initCounter(int initValue){
counter = initValue;
}
public void incCounter(){
counter++;
}
public void decCounter(){
counter--;
}
public void printCounter(){
System.out.println(counter);
}
}
If I understand you correctly, you need to send a variable into the methods so that they can modify it. As I understand, here it could be difficult becuause if you use wrapper types, they can't be modified. In such a case you can create a class that wraps your variable and can change it's values or you can use ready-to-go solutions from third party libraries.
For example, in apache-comons, they have a package:
org.apache.commons.lang3.mutable
That contains mutable wrappers for all primitive types(e.g. MutableInt).
Using your own wrapper or this classes you can modify variable inside methods and keep result saved without returning new values from these methods.
You can do , here an example :
public class PassingV {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI(1);
return a;
}
public PassingV secondM(PassingV a){
a.setI(2);
return a;
}
public PassingV thirdM(PassingV a){
a.setI(3);
return a;
}
#Override
public String toString() {
return "PassingV [i=" + i + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
Becarful to the types of objects you are using and becarful at the methods (accessors for example ) you define ,or not define in the class .
They can totally change the way how your object has seen from the outside .
Lets modifiy our class a bit and lets see what happen .
Now instead of int i will use a String parameter.
public class PassingV {
private String i;
public String getI() {
return i;
}
public void setI(String i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI("HEY ");
//substring but it return the original value :D
System.out.println(a.getI().substring(2));
return a;
}
public PassingV secondM(PassingV a){
a.setI("JOE ");
return a;
}
public PassingV thirdM(PassingV a){
a.setI("LETS GO");
return a;
}
#Override
public String toString() {
return this.getI() ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
As you can see with String object something changed , it happen because is
Immutable object
Following this link you can read more about Immutable Objects
I have defined the following two classes:
public abstract class Subject {
private ArrayList<ClockObserver> clockObserverList = new ArrayList<ClockObserver>();
public void attach(ClockObserver clockObserver) {
// begin-user-code
// TODO Auto-generated method stub
clockObserverList.add(clockObserver);
// end-user-code
}
public void dettach(ClockObserver clockObserver) {
// begin-user-code
// TODO Auto-generated method stub
clockObserverList.remove(clockObserver);
// end-user-code
}
protected void notify() {
// begin-user-code
// TODO Auto-generated method stub
for(int i= 0; i < clockObserverList.size(); i++)
{
clockObserverList.get(i).update();
}
// end-user-code
}
}
and
public class SystemClock extends Subject {
private int hour;
private int minute;
private int second;
public void setTime(int hour, int minute, int second) {
this.hour = hour;
this.minute= minute;
this.second = second;
notify();
}
public ClockTime getTime() {
ClockTime clockTime = new ClockTime();
clockTime.hour = this.hour;
clockTime.minute = this.minute;
clockTime.second = this.second;
return clockTime;
}
public void displayTime() {
System.out.println("Time is :" + this.hour + ":" + this.minute + ":" + this.second);
}
}
I got the following error for notify function:
Multiple markers at this line
- Cannot override the final method from Object
- overrides java.lang.Object.notify
- Cannot reduce the visibility of the inherited method from
Even when I change its visibility from protected to public, I still have the following error:
Multiple markers at this line
- Cannot override the final method from Object
Could you please help me what is the problem?
In Java, every class implicitly extends the Object class, which defines a method called notify. Therefore if you create a method notify in your class, the compiler will think that you tried to override the Object.notify method, which is obviously not the case.
Just rename your method notify and you should be alright.
final methods are such methods that cannot be overriden.
You cannot override public method making it protected.
The final modifier on a method means that the method cannot and must not be overridden. So you cannot override the method notify.
Regarding the visibility, you cannot "hide" methods you override, they would still be visible anyway simply by casting the variable to the super-class.
Imagine this:
class A {
protected String toString() { return "hidden"; } // Will not compile
}
A a = new A();
Object stillA = a; // a is an instance of A, so it is an instance of Object too
stillA.toString(); // This is still accessible, since Object.toString is public
No final method in java can be overridden by a subclass. In your case you are trying to override notify method of Object class which is not possible. If you really want to use the method of the class Object, then define a new method with some other name, write your code and then call notify within your new method.
For e.g.
public void notifySubject() {
for(int i= 0; i < clockObserverList.size(); i++) {
clockObserverList.get(i).update();
}
notify();
}
I can't seem to understand why when I use println method on the quarter object, it returns the value of the toString method. I never called the toString method why am I getting the return value?
public class Main {
public static void main(String[] args) {
Quarter q = new Quarter();
Nickel n = new Nickel();
System.out.println(q);
System.out.println(n);
}
}
public abstract class Money {
private int value;
public Money(int v) {
value=v;
}
public abstract int getValue();
protected int myValue() {
return value;
}
public abstract String toString();
}
public abstract class Coin extends Money {
public Coin(int value) {
super(value);
System.out.println("I am a coin, my value is " + getValue());
}
}
public class Quarter extends Coin {
public Quarter () {
super(25);
}
public int getValue() {
return myValue();
}
public String toString() {
return "A Quarter is "+getValue();
}
}
public class Nickel extends Coin {
public Nickel () {
super(5);
}
public int getValue() {
return myValue();
}
public String toString() {
return "A "+this.getClass().getName()+ " is "+getValue();
}
}
On Refering to java docs what i undestand is that,
When you call PrintStream class print(obj) / println(obj) method then internally it called write method with arguement as String.valueOf(obj) shown below :
public void print(Object obj) {
write(String.valueOf(obj));
}
Now String.valueOf(obj) does the task of calling to String method as shown below :
/**
* Returns the string representation of the <code>Object</code> argument.
*
* #param obj an <code>Object</code>.
* #return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* #see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Because PrintStream.println has an overload that takes an Object, and then calls its toString method.
Because this is how this function operates: it formats the primitive types for you, but when you pass it an object, it will call .toString() on it.
If you don't override it, it will output the default .toString() implementation (Class#somenumber) which is not really useful...
When you are directly trying to print an object, by default it will call the toString method you need to override that toString method to print the attributes of your class.
Because all classes in java are subclasses of java.lang.Object , so whenever you try to call System.out.println() method to print object, it calls the toString() method of Object class.
For Security Reasons the method prints a hashcode, not the values of that object,
but you have inherited that method in your class and extended its definition to print object values
public String toString() {
return "A Quarter is "+getValue();
}
So you get a return value.