收藏 java新手,关于this的用法不是太懂,?
public class Dept {
}
public class Emp {
}
//////////////////////////////////////////////////////////////////////
public interface IDeptDAO extends IGenericDAO<Dept>{
}
public interface IEmpDAO extends IGenericDAO<Emp> {
}
public interface IGenericDAO<T> {
void add(T newObj);
Long remove(Serializable id);
void update(Serializable id, T newObj);
T get(Serializable id);
List<T> getAll();
}
///////////////////////////////////////////////////////////////////////////////////////
public class DeptDAOImpl extends GenericDAOImpl<Dept> implements IDeptDAO {
public DeptDAOImpl(){
super();
}
}
public class EmpDAOImpl extends GenericDAOImpl<Emp> implements IEmpDAO {
}
abstract public class GenericDAOImpl<T> implements IGenericDAO<T> {
//GenericDAOImpl<T> 里面T的真正类型的字节码;
private Class<T> clz;
public GenericDAOImpl(){
//System.out.println(this.getClass().getSuperclass());
//System.out.println(this.getClass().getGenericSuperclass());
Type t = this.getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
clz = (Class<T>) pt.getActualTypeArguments()[0];
System.out.println("--->" + clz);
}
public void add(T newObj) {
}
public Long remove(Serializable id) {
return null;
}
public void update(Serializable id, T newObj) {
}
public T get(Serializable id) {
try {
return clz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<T> getAll() {
return null;
}
}
///////////////////////////////////////////////////////////////////////////////////
public class Test {
public static void main(String[] args) {
/**
* 创建子类对象之前,会先调用父类的构造方法
*/
IDeptDAO deptDao = new DeptDAOImpl();
Dept dept = deptDao.get(123);
System.out.println(dept);
IEmpDAO empDao = new EmpDAOImpl();
Emp emp = empDao.get(222);
System.out.println(emp);
//new GenericDAOImpl();
}
}
/*我不是太了解其中this指代的对象是什么,各位大神能否为我详细解释一下this的用法,以及super的用法,?谢谢麻烦给我了!
[解决办法]
说得好 理论东西看点文章比较好 这里的人回答你的会很乱 看的你也会很乱
[解决办法]
举个短一点的例子。比如下面这个类:
public class Person {
String name;
public Person(String name) {
this.name = name;
}
public void eat() {
System.out.println(this.name + " is eating.");
}
}
如果有以下代码:
Person zhang3 = new Person("张三");
zhang3.eat();
Person li4 = new Person("李四");
li4.eat();
执行zhang3.eat()的内部代码时,this.name中的this就是指zhang3这个对象。
类似的,执行到li4.eat()时,this.name中的this此时指的是li4这个对象。
建议楼主先找本Java书籍耐心地看一遍。
[解决办法]
this就是表示正在使用的那个对象
[解决办法]
super:super关键字是只能用在具有继承关系的两个类之间
super关键字是用于继承关系中的子类中
super关键字代表父类类型的对象
super.属性===>子类引用父类的属性
super.方法===>子类引用父类的方法
super()===>子类引用父类的空的构造方法
super(参数列表)==>子类引用父类相应的构造方法
[解决办法]
楼主可以看看这个,容易理解。
[解决办法]
Java关键字this只能用于方法方法体内。当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。因此,this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this,并且this只和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this。