Re: Object reference
"frank" <frank003@gmail.com> wrote in message
news:9ec7e6ed-e72c-4de9-aab8-6dc19a151c3b@j32g2000yqh.googlegroups.com...
I'm new bee to java . In the below program I had created the parent
object in the
reference of child class. When the object creation is inside the
method. I
am not getting any error. If the object creation is in the class
level. I am
getting the error in accessing the method. tel me Why can't
access the the method in side the class..?
Thanks In Advance...
class Employee {
public void ss(){
System.out.println("Testing The Casting");
Employee mn = new Manager();
Manager t = new Manager();
Manager kk = (Manager) new Employee();
kk.manage();
}
{ " Manager kk = (Manager) new Employee();
kk.manage(); " } -------------- Error in this line..
}
class Manager extends Employee {
public void manage() {
System.out.println("Managing ...");
}
}
First, I recommend that you read the following article:
http://pscode.org/sscce.html
Second, the statement that you flagged as "Error in this line" is inside an
instance initializer of the class. You are not ready to start using
instance initializers, because you do not understand the relationship
between classes and instances. As you said, you are new. Nothing wrong
with being new--we all had to start sometime.
On your list of things to study and try, put instance variables (also known
as fields) real soon. You cannot begin to understand OO until then. After
that, study inheritance and then casts. Sometime later, study contructors,
static fields and static methods. Stay away from initializers for a long
time.
You are also not quite ready to experiment with casts. Study instance
variables and inheritance before casting.
Here are some simple models of class declarations:
class SomeClass {
public void someMethod() {
// Declare local variables here.
int var1 = 7;
String var2 = "Howdy";
// Do some things with local variables.
}
}
class AnotherClass {
// instance variable declarations go here
private int intVar1 = 12;
private String strVar1 = "Kumquat";
public void method1() {
// Declare local variables here.
int j = 0;
String s = "ABCDE";
// Do some things with local variables.
// Do some more things with instance variables.
}
public returnType method2() {
// Declare local variables here.
// Do some things with local variables.
// Do some more things with instance variables.
return someThing; // Must match returnType
}
Pretend that you must do all of the following:
1. Declare instance variables before methods.
2. Include "private" before every instance var declaration.
3. Include "public" before every method declaration.
4. Declare local variables inside the method body before any statements.
5. Include an explicit initial value for every variable in its declaration.
6. Fully declare every variable on its own line.
These rules will save you a lot of grief.
Good luck!