如何在不创建子类对象并引用其自己的对象的情况下为抽象类创建对象
例如:
public class abstract student{
private int sno;
private String sname;
}
public class Test{
public static void main(String[] rs )
{
Student s= new Student();// it is not working
}
}
无需创建子类或实现类,我需要解决方案
答案 0 :(得分:0)
abstract
类的想法是显式防止实例化它。真的就是抽象了。
但是您可以匿名对其进行子继承:
Student student = new Student() { };
这将创建Student
的新的,无名的扩展名。
答案 1 :(得分:-1)
<code>
package com.glen;
public abstract class student {
private final int sno;
private final String sname;
public int getSno() {
return sno;
}
public String getSname() {
return sname;
}
public student(int sno, String sname) {
super();
this.sno = sno;
this.sname = sname;
}
@Override
public String toString() {
return "student [sno=" + sno + ", sname=" + sname + "]";
}
}
-----------------------
package com.glen;
public class Test {
public static void main(String[] args) {
student s=new student(10,"raja") {};
System.out.println(s);
}
}
</code>