This question already has answers here:
why java polymorphism not work in my example
(3 answers)
Closed 7 years ago.
I've been struggle to understand something that I'm sure is very simple, yet I'm newbie in java so I'm asking you guys:
public class A
{
public int num;
/**
* Constructor for objects of class A
*/
public A(){
num = 222;
}
public A(int n){
num = n;
}
public int getNum(){
return num;
}
public boolean f(A a){
return num == a.num*2;
}
}
public class B extends A
{
public int num;
public B(int n)
{
num = n;
}
public boolean f(B b){
return num == b.num;
}
}
public class Tester
{
public static void main(String[]args){
A a = new B(14);
System.out.print(a.num);
}
}
The output of this is: 222.
My question is why is 222 and not 14?
I did put constructor inside B that gets int, and I put that int(14) in a b constructor. So why do I get the result as if I used empty A contractor?
Can anyone please explain me the logic of this?
Thanks!
because you have two variables num and as you upcasting your object to A you are using variable from class A which holds only default value
Related
Interface and a class Number1, later Number2, etc.
When I try to use member data inside method add(), it demands that I cast it first to class type.
However if I use member method inside method add(), it does not demand that I cast to class type.
Any explanation will be appreciated.
Code below attached.
package mynums;
//Interface for all my number types, Number1, Number2 (not shown), etc
public interface NumberIF
{
public int getNum();
public void setNum(int numx);
//I will have other types of numbers not just Number1.
//I will have Number2, etc.
public void add(NumberIF f1, NumberIF f2);
public void print();
}
package mynums;
//There will be other types of numbers Number2, Number3
//all doing these operations but different.
//This is just to test the concept.
//But I have a problem here.
public class Number1 implements NumberIF
{
private int num;
public Number1()
{
num = 1;
}
public Number1(int numx)
{
num = numx;
}
public int getNum()
{
return (num);
}
public void setNum(int numx)
{
num = numx;
}
public void add(NumberIF f1, NumberIF f2)
{
int numt;
/**
* Why to use member variables I must specify the type of class.
* Why to use member method I do not have to specify type of class.
*/
//numt = f1.num + f2.num; ERROR
// either one works
//Why accessing member data is different from accessing member method.
numt = ((Number1)f1).num + ((Number1)f2).num;
numt = f1.getNum() + f2.getNum();
num = numt;
}
public void print()
{
System.out.println(num);
}
static public void main(String[] args)
{
Number1 f1, f2, f3;
f1 = new Number1(1);
f2 = new Number1(2);
f3 = new Number1(0);
f3.add(f1, f2); // 1 + 2= 3
f3.print();
}
}
Java is a statically-typed language.
Variables of static type NumberIF do not necessarily point to objects of type Number1, so those objects may not have the field num.
You only get to use the members of the static type (and its supertypes) of the variable.
This question already has answers here:
What are Generics in Java? [closed]
(3 answers)
Closed 3 years ago.
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code
public class Test1
{
public static void main(String args[])
{
Thing whipersnaper = new Thing(30, "whipersnaper");
List storage = new List();
storage.insert(whipersnaper);
Thing x = storage.getItem(0);
x.doubleWeight();
System.out.println(x.getWeight());
}
}
here is the "Thing" class
public class Thing
{
private int weight;
private String name;
public Thing(int weight,String name){
this.weight = weight;
this.name = name;
}
public void doubleWeight(){
this.weight *= 2;
}
public int getWeight(){
return this.weight;
}
}
finally here is the List class
public class List
{
private Object[] itemList;
private int size;
public List()
{
this.itemList = new Object[10];
this.size = 0;
}
public void insert(Object item){
itemList[size] = item;
size++;
}
public Object getItem(int index){
return itemList[index];
}
}
i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.
Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);
Thing x = (Thing) storage.getItem(0);
When i call s1.dub(7) or s2.dub(7) it doesn't work
,but calling it with a string like s2.dub("9") works and prints the doubled string
Could any one tell me why?
Here's the code
interface Inter {
int number();
}
abstract class Abs {
static int foo = 12;
int number() { return 5; }
abstract int ace();
}
final class Sub extends Super {
Sub(int bar) { foo = bar; }
public int number() { return 10; }
int ace() { return 13; }
int dub(int i) { return 2 * i; }
}
public class Super extends Abs implements Inter {
public int number() { return 11; }
public static void main(String args[]) {
Super s1 = new Super();
Super s2 = new Sub(16);
//System.out.println(s1.dub(7)); //doesn't work
//System.out.println(s2.dub(7)); //doesn't work
//System.out.println(s1.dub("7")); //works giving 77
//System.out.println(s2.dub("7")); //works giving 77
}
int twice(int x) { return 2 * x; }
public int thrice(int x) { return 3 * x; }
int ace() { return 1; }
String dub(String s) { return s + s; }
}
Very easy.. you class Super defines a method:
String dub(String s) { return s + s; }
in your main method you instantiate Super:
Super s1 = new Super(); // this has a dub( String ) method
then you try to call this method (dub) passing a integer, instead of a string:
System.out.println(s1.dub(7)); // s1.dub(...) takes a String, not a number
EDIT: This code should not compile, or run, because you are assigning both instances to the super class Super (which does not define a dub(int) method).
Not sure how you are getting exceptions?
Thank you #Jean-FrançoisSavard - I totally missed that!
EDIT2: The original question was modified and no longer indicates that an exception is thrown, which makes sense as the code should not compile at all.
EDIT3: (last one, due to original question changing)
System.out.println(s1.dub(7)); //- this will never work unless you change your class' definition
System.out.println(s2.dub(7)); //- will work if you also change the following line:
from:
Super s2 = new Sub(16);
to:
Sub s2 = new Sub(16);
Let's say, 5 is considered a good number. A method is to define to check a number is good or not. Parameter type int and return type is boolean. If argument is 5 it will return true and false otherwise.
See this code:
class Library{
boolean isGood(int num){
return num==5;
}
}
public class String_handling {
public static void main(String[] args) {
int num=8;
System.out.println(new Library().isGood(num));
}
}
I know this code is okay.
But I want to define a method such that I can invoke in this way:
System.out.println(num.isGood());
As work on string like this:
MyString.contains("xy");
MyString.substring(0,4);
Is there any way? Give an example.
Since int is a primitive, the only way you can to that, is to make your own class MyInteger and add your method isGood(), like so
public class MyInteger{
private int num;
public MyInteger(int num){
this.num = num;
}
public boolean isGood(int num){
return this.num == num;
}
}
I am new to concepts of java. while preparing my first program of classes with objects i encountered a problem. here is the code and the error..please resolve..
PROGRAM:
class Fact
{
private int i;
private int n;
private int fact;
public Fact()
{ fact=1;
i=1;
}
public Fact( int x)
{ n=x; }
public void getAnswer()
{
while(i<=n)
{fact=fact*i;
i++;}
System.out.println(fact);
}
}
class FactMain
{
public static void main(String dt[])
{
Fact obj= new Fact(6);
obj.getAnswer();
}
}
ERROR:
Main method not found in class Fact, please define the main method as:
public static void main(String[] args)
just change your Parameterized constructor to this
public Fact(int x) {
fact = 1;
i = 1;
n = x;
}
because you declare factorial in default constructor and you are not calling it. So, 0 is assigned to factorial and then you r trying to multiply it. Which makes no sense.
Rename the class file name Fact.java to FactMain.java.
private int fact;
public Fact()
{ fact=1;
i=1;
}
public Fact( int x)
{ n=x; }
Note, your default constructor set fact but constructor Fact( int x) set n. Hence fact is 0. So your output is 0 too.
Solution:
public Fact(int x) {
fact = 1;
i = 1;
n = x;
}
Or,
public Fact(int x) {
this(); // default constructor
n = x;
}
Here is the complete solution:
Create a single class file named FactMain.java, then paste the following code:
class Fact {
private int i;
private int n;
private int fact;
public Fact() {
fact = 1;
i = 1;
}
public Fact(int x) {
this();
n = x;
}
public void getAnswer() {
while (i <= n) {
fact = fact * i;
i++;
}
System.out.println(fact);
}
}
class FactMain {
public static void main(String[] dt) {
Fact obj = new Fact(6);
obj.getAnswer();
}
}
Your main method is in FactMain.java, but you are saving a file as Fact.java.
You will need to save the file as FactMain.java as JVM expects main to be in the same class as the name of .java file.
You have saved your file as Fact.java. So java is trying to find the main class in Fact. Save your file as FactMain.java It should work.
You have defined your main class in FactMain and most probably after compilation while running you're trying to execute
java Fact
And hence you got the error because there is no main method in Fact class.
Once you compile the .java file you will get two class files Fact.class and FactMain.class so you should execute
java FactMain
Move the FactMain class to FactMain.java
FactMain.java
public class FactMain
{
public static void main(String dt[])
{
Fact obj= new Fact(6);
obj.getAnswer();
}
}
Allow the Fact class to remain in the Fact.java file
Fact.java
public class Fact {
private int i;
private int n;
private int fact;
public Fact() {
fact = 1;
i = 1;
}
public Fact(int x) {
this();
n = x;
}
public void getAnswer() {
while (i <= n) {
fact = fact * i;
i++;
}
System.out.println(fact);
}
}
Compile the classes...
javac {package path}\FactMain.java
Run the main class
java {package path}.FactMain