Typing By Casting To Interface

Jun 16, 2014

I'm looking for a heuristic explanation of how to think of an "interface" as a type. I'm used to think of the 'type' of a class coming form its very definition but I often see casting to an interface which I still feel very uncomfortable about.Other than an interface, are there other unusual ways a 'type' may be referred to?

A second basic question: When you user 'super.f()', will Java go up the calling chain until it finds method 'f' (and report an err if none is found) or does it expect to find 'f' immediately at its very first parent?

View Replies


ADVERTISEMENT

Typing Double Name In The String

Oct 26, 2014

I am making a program where the user types in how many students, the student name and the student result. My problem is typing in a dobule name for instance: Tom Tom.

I have tried both:

String name = input.Next(); -> Only works with one name.
and
String name = input.nextLine(); -> Skips right trough and ask me to type result again.

Here is my code:

Java Code:

import java.util.Scanner;
public class c5e8 {
public static void main(String[]args){
Scanner input = new Scanner (System.in);
int highestResult = 0;
String highestName = " ";

[Code] ....

View Replies View Related

While Loop Keeps Running After Typing Quit?

Feb 15, 2014

The while loop keeps running although I type quit. What is wrong with this code?

import java.util.*;
 
public class OddEvenGame {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
 
]Code] ....

View Replies View Related

Casting For CompareTo

Nov 11, 2014

I am trying to compare some items from a generic arraylist with each other, but I keep getting an error stating that I need to cast the values in line 38. However, when I heed the warning and change it to what it wants, I get a warning stating "type safety: Unchecked cast from K to Comparable<K>". Should I ignore this warning or is there a better way to compare the two items? Also, is there another way for me to use compareTo w/o making my class extending/implementing comparable or is that the only way?Here is what I have:

class WordInfo<K, V extends Comparable <K>> {
private FileReader fr;
private String word;
private ArrayList<K> list;
private BufferedReader br;
private int current = 0;

[code]....

View Replies View Related

Casting Exception In Generics

Jan 29, 2014

I have studied that Generics are used to shift the Class Cast Exception into Compile time errors , So that we get errors at compile time error and we do correct them before executing ,but Here is a program in which i am getting Class Cast Exception

class Animal
{
}
class Dog extends Animal
{
}
class Cat extends Animal

[code]..

Getting Exception at line no 29 which i know why it occurs but just wanna ask that isn't it should be caught at compile time According to Generics ?

View Replies View Related

Implicit And Explicit Casting

Aug 21, 2014

The following code snippet will print 'true'.

short s = Short.MAX_VALUE;
char c = s;
System.out.println( c == Short.MAX_VALUE);

Correct Option is : B

A. True

B. False

Explanation:

This will not compile because a short VARIABLE can NEVER be assigned to a char without explicit casting. A short CONSTANT can be assigned to a char only if the value fits into a char.

short s = 1; byte b = s; => this will also not compile because although value is small enough to be held by a byte but the Right Hand Side i.e. s is a variable and not a constant. final short s = 1; byte b = s; => This is fine because s is a constant and the value fits into a byte. final short s = 200; byte b = s; => This is invalid because although s is a constant but the value does not fit into a byte. Implicit narrowing occurs only for byte, char, short, and int. Remember that it does not

occur for long, float, or double. So, this will not compile: int i = 129L;The below code compiles fine and contradicts what is said in bold. So what does the bold statement mean then?

Java Code: class BreakTest{
public static void main(String args[])
{
float f=1.0f;
double d=f;
}
} mh_sh_highlight_all('java');

View Replies View Related

String Input / Output And Casting

Oct 2, 2014

I have to create a program that uses the Scanner in String input and Output that will enable the user to convert

double -> int
int -> byte
int -> short
int -> hex-string

The output should look something like this:

Syntax: convert <value> <type>
convert 15.5 int~> 16
convert 128 byte~> -128
<type>: int, byte, short, hex, decimal
Syntax: max <type>
max byte~> 127
<type>: int, byte, short

[Code] ....

View Replies View Related

If Statement - Char To String Casting?

Aug 3, 2014

import java.io.IOException;
import java.util.*;
public class Guesser {
public static void main(String[] args) throws IOException {
 char[] alphabet = "abcdefghijklmnopqrstuvwxyz1234567890 .,:;'-".toCharArray();

[Code] .....

I'm writing a program which will take a three letter word (for now) and then try to guess the word over and over again until it finds it, then print the word and the amount of tries it took to find it.

The problem: at the moment the program will find the word but not break out of the for loop when it does. I think it doesn't like the char to String conversion somewhere along the line.

View Replies View Related

How To Apply Casting Correctly For HeightProgram

Mar 17, 2014

how to calculate the child's height in float value fixing value where if you choose male the accurate value, but if you choose female the value will be accurate too.

int heightMother, heightFather;
int heightMaleChild, heightFemaleChild;
String gender;

[code]....

View Replies View Related

Servlets :: Why Session Not Type Casting Into String

Oct 17, 2014

why my session not type casting into String? I'm placing that code below where problem arised.

HttpSession hs1=request.getSession(false);
out.println("hi");
String t1=(String)hs1.getAttribute("name");
out.println("hi "+t1);

in my above code first "hi" is printed successfully but next statement arises type cast exception.

View Replies View Related

Casting To Parameterized Types And Unchecked Warnings

Jul 15, 2014

There is a sentence in JLS 7 which I can't figure it out. It says :

A cast from a type S to a parameterized type T is unchecked unless at least one of the following conditions holds:
-S <: T
-All of the type arguments (§4.5.1) of T are unbounded wildcards
-T <: S and S has no subtype X other than T where the type arguments of X are not contained in the type arguments of T.

Condition one and two I got it. But the number three is really bugging me. I write some code in order to try to understand it.

class G<X>{}
class D<T,U> extends G<T>{}
G<String> g = new G<>();
D<String, Integer> dd = (D<String, Integer>) g;

In Eclipse I got no warning but it shouldn't give one ?

Because g has others subtypes than D<String, Integer> (e.g. D<String, List> , D<String, G>)

Am I missing something about the contained type arguments ?

View Replies View Related

Casting And Interfaces - Comparing Object Of Unknown Types

Oct 15, 2014

import java.util.*;
public class CommonElements
{
private int comparisons; // number of comparisons made
private Comparable[] arrayToSearch; // current array being traversed
private Comparable[] commonElements = new Comparable[10];
private int arrayPosition = 0; //keeps track of what index to add an element to common at

[Code] ...

I have trying to get this down to the bar minimum. I am trying to cast the desired object array to a array of comparable. This is all required by the assignment.

I am getting a runtime error that I can not perform the desired cast. What do I need to provide the compiler in order to allow for this casting. I can not change the signature of the method however nothing about the class has been specified do I need to implement comparable? Also I don not now what the client is passing so how would I write a generic compareTo method to compare object of unknown types.

View Replies View Related

Type Casting - Getting Number With Two Decimal Places As Output?

Jun 7, 2013

"Type Casting" .... So the question is "How am I getting a number with two decimal places as output?"

import java.util.Scanner;
public class SalesTax
{
public static void main(String[] args) {
double purchase, tax;
Scanner input = new Scanner(System.in);
System.out.print("Enter purchase amount: ");
purchase = input.nextDouble();
tax = purchase * 0.06;
System.out.println("Sales Tax: $" + (int)(tax * 100) / 100.0); +//this will give two decimal places??+
}
}

View Replies View Related

Interface Extends More Than One Interface

Jun 9, 2014

Below code gets printed as output?

public interface I1 {
public void method();
}
public interface I2 {
public void method();
}
public interface I3 extends I2, I1 {

[Code] ....

View Replies View Related

Using Methods Of Interface

Feb 5, 2014

I have following code. In this code CSClient is an interface. All methods of CSClient are implementaed in CSClientImpl class. Do I not need CS Client Impl imported in this code ?

How can I call getBranch() of CSClient, which is not implemented in CSClient as " this. getCsClient(). get Branch (new CSVPath(vpath), true);" ? This code works fine without any error in eclipse.

How can a method getBranch(), which is implemented in CSClientImpl class be used in this code without importing CSClientImpl ?

package com.rbc.teamsite.client;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

[code]....

View Replies View Related

Variables In Interface

Jan 21, 2015

Variables defined in interface are public static and final so I was thinking that we should not be able to override the variables in a class thats implementing the interface. But when I am compiling the below class, it compiles fine and gives the correct values. but when I did disp.abhi = 35; it gives a compile error (cannot override final variable)

interface display{
int abhi = 10;
void displayName();

[code]....

View Replies View Related

What Is Marker Interface

Nov 24, 2014

what is marker interface?i want to know internal implemenatation and how to write custom marker interface?

View Replies View Related

Interface As Object?

Aug 6, 2014

I'm having trouble understanding the concept of the interface Connection, and PreparedStatement.

1) The simplest way to put it is how is it possible that this code is creating Connection and PreparedStatement objects? I was always under the impression that interfaces cannot be instantiated, but rather implemented. For example I don't see "public class Prepared implements Connection", or "public class Prepared implements PreparedStatement", But I see "Connection con = null;" and "PreparedStatement pst = null;". So it seems as if the interfaces are being used to create objects called con and pst.

2) If in fact these interfaces are being implemented, where are the method blocks in this code that should have been added in order to fulfill the contract?

package zetcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

[code]....

View Replies View Related

Concept Of Interface

Aug 22, 2014

I am not getting the concept of interfaces.I know they are used to implement multiple inheritances.I also know the example that we create an interface car with certain methods so that a class like bmw which implements the car interface has to implement these methods.But I don't know how interfaces come handy?I don't know the meaning of a class calls a method using an interface?(i know that an interface can not be instantiated).

View Replies View Related

Implementing Comparator Interface?

Mar 7, 2014

overriding of the compare method.

Here's an example I found:

public class Someone {
String name;
int age;
ArrayList <Someone> listarr = new ArrayList <Someone>();
public Someone(String name1, int age1) {
name = name1;
age = age1;

[code]...

1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?

2. Why do we use the class name for the generics?

View Replies View Related

Interface Not Updating Properly

Mar 20, 2015

The program runs well , it adds the applet but it dosn't update the interface unless I press "_"(Minimize) . To be more clear , the object paints a spring wich goes through 4 stages , it is added to the JFrame but it dosn't uptade until I minimize the frame , that is when it goes to the next stage .

The main class which calls the spring to be added to the frame :

public class principal implements ActionListener ,Runnable{
JTextField field;
JFrame frame;
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
  frame.repaint();

[Code] .....

View Replies View Related

When To Use Interface And Abstract Class

Apr 17, 2014

I know whats the interfaces and abstract class and also know that difference between interface and abstract class,but here my doubt is eventhough abstract class more advantage than the interface,then why should we use interfaces and when?

View Replies View Related

Instantiating Interface - ActionListener

Dec 25, 2014

I have a snippet here that I'm working with and I have a few questions about it.

button.addActionListener( new ActionListener(){
@Override
public void actionPerformed(ActionEvent ev){
System.out.println("Button Pressed");
}
});

My questions are:

1. How is it possible to use new on ActionListener when ActionListener is an Interface, not a Class. Isn't it illegal to instantiate an Interface?

2. What is going on with the argument to addActionListener? We have the new ActionListener, but we also have a method being defined as well?

View Replies View Related

Implementing Custom Map Interface

Nov 5, 2014

I am supposed to implement a custom Map interface and I'm having some trouble with this method:

// 1. From the interface
/**
* Gives an iterator iterating over the key set from the smallest key that is not less than the key provided.
* @param key the key
* @return the iterator
* @throws NullPointerException if key == null
*/

public Iterator<Key> tailIterator(Key key);

[Code] .....

My implementation is wrong according to a JUnit test. Also, to get a full score this method should have a worst case running time of O(log N), which obviously isn't the case now. (My Map implementation is currently based on binary search in an ordered array, keeping a prallel array for the values).

View Replies View Related

Can Interface Extend A Class

May 16, 2014

Can an interface extend a class?When I am running the following code it's showing some errors..I have commented them.

class A {
public void methodA() {
System.out.println("Class A methodA");
}
}
interface B extends A //interface expected here {
public void methodA();

[code]....

View Replies View Related

Typecasting Interface To ArrayList?

Dec 16, 2014

Can i type cast a interface to ArrayList? suppose there is a interface Named Node.

public interface Node
{
public static final short ELEMENT_NODE=1;
......
.....
}

i want to typecast this interface to ArrayList and fetch all the value.You can use hashtable object class etc.my main moto is to take a value in ArrayList and traverse it.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved